链栈实现的括号匹配 不知道哪里出错了
- C/C++ code
#include<stdio.h>#include<stdlib.h>#define OK 1#define ERROR 0#define true 1#define false 0typedef char status;typedef char ElemType;typedef struct StackNode{ ElemType date; struct StackNode *next;}StackNode,LinkStack;int InitStack(LinkStack *top){ top->next=NULL; return OK;}int PushStack(LinkStack *top,ElemType e){ StackNode *temp=malloc(sizeof(StackNode)); if(!temp) return ERROR; temp->date=e; temp->next=top->next; top->next=temp; return OK;}int PopStack(LinkStack *top){ StackNode *temp=malloc(sizeof(StackNode)); temp=top->next; top->next=temp->next; free(temp); return OK;}int StackEmpty(LinkStack *S){ if(S->next==NULL) return OK; else return ERROR;}status GetTop(LinkStack *S,ElemType *e){ if(S->next==NULL) return ERROR; *e=S->next->date; return OK;}int Matching(){ int flag=1; ElemType c,x; LinkStack *S=malloc(sizeof(StackNode)); c=getchar(); while(c!='#'&&flag) { switch(c){ case '['||'(' : PushStack(S,c); break; case ')' : GetTop(S,&x); if(!StackEmpty(S)&&x==')') PopStack(S); else flag=0; break; case ']' : GetTop(S,&x); if(!StackEmpty(S)&&x==']') PopStack(S); else flag=0; break; } c=getchar(); } if(StackEmpty(S)&&flag) return true; else return false;}int main(){ if(Matching()) printf("匹配成功!\n"); else printf("匹配失败!\n"); return 0;}
[解决办法]
貌似匹配思想错了 程序没怎么看
if(!StackEmpty(S)&&x==')')应该是if(!StackEmpty(S)&&x=='(')下面还有个类似的