链栈的括号匹配

#include

using namespace std;

template
struct node
{
t data;
node *next;
};
template
class linkstack
{
public:
linkstack(){top=NULL;} //构造函数,建立空栈
~linkstack(); //析构函数,释放链栈中各结点的存储空间
void push(t x); //元素x入栈
t pop(); //栈顶元素出栈
t gettop(){if(top!=NULL)return top->data;}; //取栈顶元素(并不删除)
int empty(){return topNULL?1:0;} //判空操作
private:
node *top;
};
template
void linkstack::push(t x)
{
node *s;
s=new node;s->data=x;
s->next=top;top=s; //将结点s插在栈顶
};
template
t linkstack::pop()
{
t x;
node *p;
if(top
NULL)throw"下溢";
x=top->data;p=top;
top=top->next;
delete p;
return x;
};
template
linkstack::~linkstack()
{
node *q;
while(top!=NULL)
{
q=top;
top=top->next;
delete q;
}
};
bool matching(char exp[]) //括号匹配
{
int state=1,i=0;
char ch,e;
ch=exp[i++];
linkstackS;
while(ch!=’\0’&&state)
{
if(ch==’)’||ch==’[’)S.push(ch);
else if(ch==’)’)
if(!S.empty()&&S.gettop()’)’)e=S.pop();else state=0;
else if(ch
’]’)
if(!S.empty()&&S.gettop()==’]’)e=S.pop();else state=0;
ch=exp[i++];
}
if(state&&S.empty())return true;
else return false;
};
int main()
{
linkstackA;
cout<<“若为空栈输出1,非空输出0:”<<A.empty()<<endl;
cout<<“建立栈,栈元素:{’(’,’[’,’]’,’(’,’)’,’)’};”<<endl;
char ch1[6]={’)’,’)’,’(’,’]’,’[’,’(’};
for(int i=0;i<6;i++)A.push(ch1[i]);
cout<<“若括号匹配输出1,否则输出0;”<<endl;
cout<<matching(ch1)<<endl;
cout<<“栈顶元素为:”<<endl;
cout<<A.gettop()<<endl;
cout<<“栈内元素依次为:”<<endl;
for(int i=6;i>0;i–)cout<<A.pop()<<’ ';
cout<<endl;
cout<<“若为空栈输出1,非空输出0:”<<A.empty()<<endl;
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值