算法:假设表达式中包含两种括号:圆括号、方括号和大扩号。检验括号是否匹配可以用堆栈来实现当遇到 ( 或 [或{ 时进栈,遇到 ] 或 ] 或}时出栈进行匹配检验,如果出现不匹配的情况立即结束,否则继续取下一个字符。如果没有遇到不匹配的情况,最后判断栈是否为空,栈为空,括号匹配,否则不匹配
源代码:
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define OVERFLOW -2 #define NULL 0 typedef int Status; #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 typedef char SElemType; typedef struct{ SElemType *base; //栈底指针 SElemType *top; //栈顶指针 int stacksize; //栈容量 }SqStack; Status InitStack(SqStack &S){ //构造空栈S S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType)); if(!S.base)exit(OVERFLOW); //存储分配失败 S.top=S.base; //空栈 S.stacksize=STACKINCREMENT; return(OK); }//InitStack Status Push(SqStack &S, SElemType e){ //插入e为栈顶元素 if(S.top-S.base==S.stacksize){//栈满则应重新分配空间 S.base=(SElemType *) realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType)); if(!S.base)exit(OVERFLOW); S.top=(S.base+S.stacksize);//使得S.top重新指向栈顶,因realloc S.stacksize+=STACK_INIT_SIZE; } *S.top++=e; //top指向待插入位置 return(OK); }//Push Status Pop(SqStack &S,SElemType &e){ //若栈不空则栈顶元素出栈并用e带回其值 if(S.top==S.base)return ERROR; e=*(--S.top); //栈顶元素为*(S.top-1) return OK; } Status StackEmpty(SqStack S){ if(S.top==S.base)return OK; return ERROR; }//StackEmpty Status match(char *str ) { SqStack S; InitStack(S); int i, count; char e,c; i=0; count=0; while(c=str[i++]&&count==0){ switch(c){ case '(': case '[': case '{': Push(S,c);break; case '}': if(StackEmpty(S)) {count++;break;} else{ Pop(S,e); if(e!='{') {count++;break;}} case ']': if(StackEmpty(S)) {count++;break;} else{ Pop(S,e); if(e!='[') {count++;break;}} case ')': if(StackEmpty(S)) {count++;break;} else{ Pop(S,e); if(e!='(') {count++;break;}} default :break; }//switch if(count==0&&StackEmpty(S)) printf("The string is match!\n"); else printf("The string is not match!\n"); return OK; } } void main() { char str[100]; int count; SqStack S; InitStack(S); printf ("Please input the string:"); scanf ("%s",str); match(str); }