#define Stack_Size 50/*括号匹配操作*/ #define FALSE 0 /*2009.08.13王红刚*/ #define TRUE 1 typedef char StackElemType; typedef struct { StackElemType elem[Stack_Size];//用数组模拟栈 int top; }SeqStack; void InitStack(SeqStack *s)//初始化 { s->top=-1; } int IsEmpty(SeqStack *s) { if(s->top==-1) return TRUE; else return FALSE; } int Push(SeqStack *s,StackElemType x)//入栈操作 { if(s->top==Stack_Size-1) return FALSE; s->top++; s->elem[s->top]=x; return TRUE; } int Pop(SeqStack *s,StackElemType *x)//出栈操作 { if(s->top==-1) return FALSE; else { *x=s->elem[s->top]; s->top--; return TRUE; } } int GetTop(SeqStack *s,StackElemType *x)//取栈顶元素 { if(s->top==-1) return FALSE; else { *x=s->elem[s->top]; return TRUE; } } /*进行匹配*/ int Match(char ch,char str) { if(ch=='(' && str==')') { return TRUE; } else if(ch=='[' && str==']') { return TRUE; } else if(ch=='{' && str=='}') { return TRUE; } else return FALSE; } void BracketMatch(char *str)//用堆栈技术检查括号匹配 { SeqStack s; int i; char ch; InitStack(&s); for(i=0;str[i]!='#';i++) { switch(str[i]) { case '(': case'[': case '{': Push(&s,str[i]);break; case')': case']': case'}': if(IsEmpty(&s)) {printf("/n 右括号多余!"); return;} else { GetTop(&s,&ch); if(Match(ch,str[i])) Pop(&s,&ch); else { printf("/n左右括号不同类!"); return; } } } } if(IsEmpty(&s)) printf("/n括号匹配!"); else printf("/n左括号多余!"); } void main() { char str[100]; printf("please input(use the '#' end!):");//用#号结束 gets(str); BracketMatch(str); }