学习分享
本周学习的是数据结构的括号匹配,所谓括号匹配指的是在命令端输入一行只含有括号的代码,然后运行代码,判断每一个左括号是否有一个右括号与之对应,从而判断输入的数据是否违法
代码如下:
#define MAXSIZE 100 #define OK 1 #define ERROR 0 #include#include #define OVERFLOW 0 using namespace std; typedef char SElemType; typedef int Status; typedef struct{ SElemType *base; SElemType *top; int stacksize; }SqStack; Status InitStack(SqStack &S) { S.base=new SElemType[MAXSIZE]; if(!S.base) exit(OVERFLOW); S.top=S.base; S.stacksize=MAXSIZE; return OK; } Status Push(SqStack &S, SElemType e)//入栈操作 { if(S.top-S.base==S.stacksize) return ERROR; *S.top++=e; return OK; } Status Pop(SqStack &S,SElemType &e) { if(S.top==S.base) return ERROR; e=*--S.top; return OK; } SElemType GetTop(SqStack S) { if(S.top!=S.base) return *(S.top-1); } Status StackEmpty(SqStack S) { if(S.top==S.base) return ERROR; //栈空 else return OK; //栈不空 } int main() { char ch; SqStack S; InitStack(S); int flag=1; cin>>ch; while(ch!='#'&&flag) { char a='(',b='[',c='{'; switch(ch) { case '{': case '[': case '(': Push(S,ch); break; case ')': if(StackEmpty(S)&&GetTop(S)=='(') Pop(S,a); else flag=0; break; case ']': if(StackEmpty(S)&&GetTop(S)=='[') Pop(S,b); else flag=0; break; case '}': if(StackEmpty(S)&&GetTop(S)=='{') Pop(S,c); else flag=0; break; } cin>>ch; } if(!StackEmpty(S)&&flag) cout<<"匹配成功"; else cout<<"匹配失败"; return 0; }
第一步
先定义一个结构体,里面有两个指针;并初始化栈。第二步
接着构建以下四个方法,入栈Push,出栈Pop,获取站内首元素GetTop,判断栈是否为空。第三步
编写主方法,运用写的四个方法来进行括号匹配,程序完成。



