棧的應用

 

  1. #include<iostream>  
  2. #include<cstdio>  
  3. using namespace std;  
  4. //ifstream cin ("c.in");  
  5. //ofstream cout ("c.out");  
  6. const int MAXSIZE=200;  
  7. class Sqstack  
  8. {  
  9.     private:  
  10.         char elem[MAXSIZE];  
  11.         int top;  
  12.     public:  
  13.         Sqstack(){top=0;}  
  14.         ~Sqstack(){};  
  15.         void SetEmpty(){top=0;}//制棧爲空  
  16.         int IsEmpty();  
  17.         void push(char e);  
  18.         char pop();  
  19.         char Getpop();  
  20. };  
  21. int  Sqstack::IsEmpty()  
  22. {  
  23.     if(top==0)  
  24.     {  
  25.         return 1;  
  26.     }  
  27.     else 
  28.     {  
  29.         return 0;  
  30.     }  
  31. }  
  32. void Sqstack::push(char e)  
  33. {  
  34.     top++;  
  35.     elem[top]=e;  
  36. }  
  37. char Sqstack::pop()  
  38. {  
  39.     char x=elem[top];  
  40.     top--;  
  41.     return x;  
  42. }  
  43. char Sqstack::Getpop()  
  44. {  
  45.     return elem[top];  
  46. }  
  47.  
  48.  
  49.  
  50.  
  51. int main()  
  52. {  
  53.     int t;  
  54.     string a;  
  55.  
  56.     cin>>t;  
  57.     int correct = 1;  
  58.     getchar();//吸收回車  
  59.  
  60.     while(t--)  
  61.     {  
  62.         Sqstack stk;  
  63.         correct=1;  
  64.  
  65.         getline(cin,a);  
  66.         for(int i=0;i<a.length();i++)  
  67.         {  
  68.             if(a[i]=='('||a[i]=='[')  
  69.             {  
  70.                 stk.push(a[i]);  
  71.             }  
  72.             else if(a[i]==')')  
  73.             {  
  74.                 if(stk.Getpop()!='('||stk.IsEmpty())  
  75.                    {  
  76.                        correct=0;  
  77.                        break;  
  78.                    }  
  79.                    stk.pop();  
  80.             }  
  81.             else if(a[i]==']')  
  82.             {  
  83.                 if(stk.Getpop()!='['||stk.IsEmpty())  
  84.                 {  
  85.                     correct=0;  
  86.                     break;  
  87.                 }  
  88.                 stk.pop();  
  89.             }  
  90.         }  
  91.         if(!stk.IsEmpty())  
  92.         {  
  93.             correct=0;  
  94.         }  
  95.         if(correct)  
  96.         {  
  97.             cout<<"Yes"<<endl;  
  98.         }  
  99.         else 
  100.         {  
  101.             cout<<"No"<<endl;  
  102.         }  
  103.     }  
  104. }  
  105.  
  106.  
  107.  
  108.  
  109.  
  110.  
  111.  
  112.  
  113.  
  114.  
  115.  
  116.  
  117.  
  118.  
  119.  
  120.  
  121.  
  122.  
  123.  
  124.  
  125.  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章