算法中设置一个栈,每次读入一个括号,若是右括号,则或者与置于栈顶的括号匹配,或者是不合法的情况,若是左括号,则入栈。若算法结束,栈是空的,则括号合法。
括号匹配函数
Status bracket_match(){SElemType brackets[100];int i;SElemType e;SqStack S;Init_Stack(S);scanf("%s",brackets);while(brackets[i]!='\0'){if(i==0&&(brackets[i]=='}'||brackets[i]==']'||brackets[i]==')'))return ERROR;else{switch(brackets[i]){case '}':Get_Top(S,e);if(e=='{')Pop(S,e);break;case ']':Get_Top(S,e);if(e=='[')Pop(S,e);break;case ')':Get_Top(S,e);if(e=='(')Pop(S,e);break; default:Push(S,brackets[i]);break;}}i++;}if(Stack_Empty(S)){Destroy_Stack(S);return OK;}else{Destroy_Stack(S);return ERROR;}
}
全部表示和实现,以及测试代码
#include<stdio.h>
#include<stdlib.h>#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define TRUE 1
#define FALSE 0
#define ERROR 0typedef int Status;
typedef char SElemType;typedef struct{SElemType *base;SElemType *top;int stacksize;
}SqStack;Status Init_Stack(SqStack &S){S.base=(SElemType*)malloc(sizeof(SElemType)*STACK_INIT_SIZE);if(!S.base){printf("Merry Error\n");exit(0);}S.top=S.base;S.stacksize=STACK_INIT_SIZE;return OK;
}Status Clear_Stack(SqStack &S){S.top=S.base;return OK;
}Status Stack_Empty(SqStack S){if(S.top==S.base){return TRUE;}else{return FALSE;}
}int Stack_Length(SqStack S){int length=0;while(S.base!=S.top){S.top--;length++;}return length;
} Status Get_Top(SqStack S,SElemType &e){if(S.base==S.top){return ERROR;}else{e=*(S.top-1);return OK;}
}Status Push(SqStack &S,SElemType e){if(S.top-S.base>=S.stacksize){S.base=(SElemType *)realloc(S.base,sizeof(SElemType)*(S.stacksize+STACKINCREMENT));if(!S.base){printf("Merroy Error!\n");exit(0);}}S.stacksize+=STACKINCREMENT;*S.top++=e;return OK;
}Status Pop(SqStack &S,SElemType &e){if(S.base==S.top){return ERROR;}e=*(--S.top);return OK;
}Status Destroy_Stack(SqStack &S){S.top=S.base;free(S.base);return OK;
}Status bracket_match(){SElemType brackets[100];int i;SElemType e;SqStack S;Init_Stack(S);scanf("%s",brackets);while(brackets[i]!='\0'){if(i==0&&(brackets[i]=='}'||brackets[i]==']'||brackets[i]==')'))return ERROR;else{switch(brackets[i]){case '}':Get_Top(S,e);if(e=='{')Pop(S,e);break;case ']':Get_Top(S,e);if(e=='[')Pop(S,e);break;case ')':Get_Top(S,e);if(e=='(')Pop(S,e);break; default:Push(S,brackets[i]);break;}}i++;}if(Stack_Empty(S)){Destroy_Stack(S);return OK;}else{Destroy_Stack(S);return ERROR;}}int main(){while(1){if(bracket_match())printf("Brackets Is OK!\n");else{printf("Wrong Brackets\n");}}return 0;
}
欢迎留言交流。。。