练习六——链式栈+括号匹配
#include <iostream>
#include <assert.h>
#include <cstring>
using namespace std;
struct StackNode{
public:
char data;
struct StackNode *link;
StackNode(char d='@',StackNode *next=NULL):data(d),link(next){}
};
class LinkedStack{
private:
StackNode *top;
public:
LinkedStack():top(NULL){}
~LinkedStack(){makeEmpty();}
void makeEmpty();
void Push(char &x);
char Pop(char &x);
char getTop(char &x) const;
char IsEmpty() const {return (top==NULL)? 1:0;}
char getSize()const;
void output();
};
void LinkedStack::makeEmpty(){
StackNode *p;
while(top!=NULL){
p=top;
top=top->link;
delete p;
}
}
void LinkedStack::Push(char &x){
top=new StackNode(x,top);
assert(top!=NULL);
}
char LinkedStack::Pop(char &x){
if(IsEmpty()){
return 0;
}
StackNode *p=top;
top=top->link;
x=p->data;
delete p;
return 1;
}
char LinkedStack::getTop(char &x)const{
if(IsEmpty()){
return 0;
}
x=top->data;
return 1;
}
void LinkedStack::output(){
StackNode *p=top;
while(p!=NULL){
cout<<p->data<<endl;
p=p->link;
}
}
int Matching(char *exp){
int state=1;int i=0;
int l=strlen(exp);
char x;
LinkedStack s;
while(i<l){
char t=exp[i];
switch(t){
case '(':
s.Push(t);
break;
case '[':
s.Push(t);break;
case '{':
s.Push(t);break;
case ')':
if(s.Pop(x)&&x=='(') {
break;
}
else {
s.Pop(x);
cout<<x<<endl;
return 0;
}
case ']':
if(s.Pop(x)&&x==']')
break;
else
return 0;
case '}':
if(s.Pop(x)&&x=='{')
break;
else
return 0;
}
i++;
}
if(s.IsEmpty())
return 1;
else
return 0;
}
int main(){
cout<<"begin"<<endl;
char exp[3];
for(int i=0;i<3;i++){
cin>>exp[i];
}
cout<<Matching(exp);
return 0;
}