1. 程式人生 > >順序棧實現括號匹配

順序棧實現括號匹配

2018-11-10-21:38:07

  1 /*********************************************************
  2     順序棧實現括號匹配。
  3     main函式操作:
  4         1.在這裡main函式內部主要以解決括號匹配問題。
  5         2.本例中包含"()""[]"{}"三種括號。
  6         3.輸入一個表示式,如果括號匹配則輸出True,否則輸出False。
  7 *********************************************************
*/ 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <iostream> 12 using namespace std; 13 typedef char SElemtype; 14 #define INITSTACKSIZE 100 15 #define STACKINCRESMENT 40 16 #define OverFlow -1 17 typedef struct { 18 SElemtype*Top;//指向棧頂 19
SElemtype*Base;//指向棧底 20 int Stacksize;//以sizeof(SElemtype)為單位 21 }Stack; 22 23 bool InitStack(Stack&S); 24 bool StackEmpty(Stack S); 25 int StackLength(Stack S); 26 bool GetTop(Stack S,SElemtype&Elem); 27 bool Push(Stack&S,SElemtype Elem); 28 bool Pop(Stack&S,SElemtype&Elem);
29 bool PrintStack(Stack S); 30 //main函式內所有資料均為測試資料,讀者可根據自己測試方式自行調換 31 32 int main() 33 { 34 Stack S; 35 InitStack(S); 36 char c; 37 string str; 38 cin>>str; 39 for(int i=0;i<str.length();i++){ 40 if(str[i]=='('||str[i]=='['||str[i]=='{'){ 41 Push(S,str[i]); 42 continue; 43 } 44 if(str[i]==')'){ 45 GetTop(S,c); 46 if(c=='(') Pop(S,c); 47 if(c=='['||c=='{') break; 48 } 49 if(str[i]==']'){ 50 GetTop(S,c); 51 if(c=='[') Pop(S,c); 52 if(c=='('||c=='{') break; 53 } 54 if(str[i]=='}'){ 55 GetTop(S,c); 56 if(c=='{') Pop(S,c); 57 if(c=='('||c=='[') break; 58 } 59 } 60 if(StackEmpty(S)) 61 cout<<"True"<<endl; 62 else 63 cout<<"False"<<endl; 64 return 0; 65 } 66 bool InitStack(Stack&S){ 67 S.Base=(SElemtype*)malloc(INITSTACKSIZE*sizeof(SElemtype)); 68 if(!S.Base) 69 exit(OverFlow);//程式異常終止 70 S.Top=S.Base; 71 S.Stacksize=INITSTACKSIZE; 72 return true; 73 } 74 75 bool StackEmpty(Stack S){ 76 if(S.Top==S.Base) 77 return true; 78 else 79 return false; 80 } 81 82 int StackLength(Stack S){ 83 int Length=0; 84 SElemtype*index; 85 for(index=S.Top;index!=S.Base;index--) 86 Length++; 87 return Length; 88 } 89 90 bool GetTop(Stack S,SElemtype&Elem){ 91 if(S.Top==S.Base) 92 return false; 93 else{ 94 Elem=*(S.Top-1); 95 return true; 96 } 97 } 98 99 bool Push(Stack&S,SElemtype Elem){ 100 if(S.Top-S.Base>=S.Stacksize){ 101 S.Base=(SElemtype*)realloc(S.Base,(S.Stacksize+STACKINCRESMENT)*sizeof(SElemtype)); 102 if(!S.Base) 103 exit(OverFlow); 104 S.Top=S.Base+S.Stacksize; 105 S.Stacksize+=STACKINCRESMENT; 106 } 107 *S.Top++=Elem; 108 return true; 109 } 110 111 bool Pop(Stack&S,SElemtype&Elem){ 112 if(S.Base==S.Top) 113 return false; 114 else 115 Elem=*--S.Top; 116 return true; 117 } 118 119 /**************************************** 120 Author:CRUEL_KING 121 Time:2018/11/10 122 Program name:順序棧實現括號匹配.cpp 123 ****************************************/