#include <iostream> using namespace std; #define STACKSIZE 10 typedef struct { int *base; int top; int StackSize; } SqList; void initStack(SqList *&s) { s=new SqList; s->base=new int(STACKSIZE); s->top=-1; s->StackSize=STACKSIZE; } void getTop(SqList *s,char &ch)//获取栈顶元素需要影响实参,故需要加& { ch= s->base[s->top]; } void pop(SqList *s,char &ch) { if(s->top==-1) return ; ch=s->base[s->top--]; } char push(SqList *s,char ch) { if(s->top==STACKSIZE-1) return 0; s->base[++s->top]=ch ; return 1; } int empty(SqList *s) { if(s->top==-1) return 1; else return 0; } void matching(char exp[])//在此函数中state表明是否匹配,但并没有输出 { int i=0; SqList *s; initStack(s); int state=1; char ch=0; while(exp[i]!=' '&&state) { switch (exp[i]) { case '(': { push(s,exp[i]); i++; break; } case')': { if(s->top!=-1) { getTop(s,ch); if(ch=='(') { pop(s,ch); i++; } else state=0; } else state=0; } } } if(empty(s) && state) cout<<"matching"<<endl; else cout<<"Not matching"<<endl; } int main() { SqList *s; char exp[]="(()()"; //initStack(s);//这个可以不要,因为 matching函数中自己调用了 matching(exp); }