/* 检测平衡符号 */ #include<stdio.h> #include<stdlib.h> struct stack; typedef struct stack * PtrToStack; struct stack{ char *Array; int TopOfStack; int Capacity; }; PtrToStack CreateStack( int MaxSize ) { PtrToStack p; p = malloc(sizeof(struct stack)); p->Array = malloc(sizeof(char) * MaxSize ); p->Capacity = MaxSize; p->TopOfStack = -1; return p; } int IsEmpty( PtrToStack s) { return s->TopOfStack == -1; } void Pop( PtrToStack s ) { if( !IsEmpty( s ) ) s->TopOfStack--; else printf("error"); } char Top( PtrToStack s ) { if( !IsEmpty( s ) ) return s->Array[s->TopOfStack]; else printf("error"); } int IsFull( PtrToStack s ) { return s->TopOfStack == s->Capacity-1; } void Push( char ch, PtrToStack s) { if( !IsFull(s) ) s->Array[++s->TopOfStack] = ch; else printf("error"); } //遇到开放符号栈空,遇到开放符号不匹配,读入完成,栈不空 int main() { int MaxSize = 10; char tmp; PtrToStack s; s = CreateStack( MaxSize ); while( ( tmp = getchar() ) != '#' ) { if( tmp == '(' || tmp == '{' || tmp == '[') Push( tmp, s ); else { if( IsEmpty(s) ){ printf("error1"); return 0; } else { switch( tmp ) { case ']': if(Top(s) != '[') { printf("error2"); return 0; } break; case ')': if(Top(s) != '(' ) { printf("error2"); return 0; } break; case '}': if(Top(s) != '{') { printf("error2"); return 0; } break; }//switch Pop(s); }//else }//else }//while if(s->TopOfStack != -1) { printf("error3"); return 0; } }
注意该算法3个error:1.读到封闭符号时,栈空error1
2.读到#栈非空error2
3.读到封闭符号,栈非空,可是不对应error3