#include<iostream>
using namespace std;
#include<stdlib.h>
typedef struct//定义栈的存储结构
{
int *base;
int *top;
int size;
}sqstack;
sqstack initstack()//对栈进行初始化
{
sqstack s;
s.base=(int *)malloc(100*sizeof(int));//对栈开辟动态空间
s.top=s.base;
return s;
}
sqstack push(sqstack s,int e)//入栈工作
{
*(s.top)=e;
s.top++;
return s;
}
int gettop(sqstack s)//出栈工作
{
if(s.base==s.top)
{
return 0;
}
return *(s.top-1);
}
sqstack pop(sqstack s)
{
s.top--;
return s;
}
int main()
{
sqstack s;//定义链表S
char c=' ';
s=initstack();
cout<<"请输入括号,以#结束"<<endl;
while(c!='#')
{
cin>>c;
switch (c)//用1.2.3.来分别代替“(”,“[”,“{”入栈;
{
case '(':s=push(s,1);break;
case '[':s=push(s,2);break;
case '{':s=push(s,3);break;
case ')':
{
if(gettop(s)==0)
{
cout<<"多了*)*"<<endl;
return 0;
}
else if(gettop(s)==1)
{
s=pop(s);
}
else
{
cout<<"括号不匹配!"<<endl;
return 0;
}
};break;
case ']':
{
if(gettop(s)==0)
{
cout<<"多了*]*"<<endl;
return 0;
}
else if(gettop(s)==2)
{
s=pop(s);
}
else
{
cout<<"括号不匹配!"<<endl;
return 0;
}
};break;
case '}':
{
if(gettop(s)==0)
{
cout<<"多了*}*"<<endl;
return 0;
}
else if(gettop(s)==3)
{
s=pop(s);
}
else
{
cout<<"括号不匹配!"<<endl;
return 0;
}
};break;
default:break;
}
}
if(s.top==s.base)
{
cout<<"括号匹配"<<endl;
}
else
{
cout<<"多了左括号"<<endl;
}
return 0;
}
本实验代码采取的思想是使用1,2,3分别代替(,[,{入栈以简化检索过程。