使用链栈完成平衡符号的检测(大,中,小括号)
基本思路与使用顺序栈完成平衡符号的检测一样,不再赘述。
整体代码:
#include<iostream>
typedef struct Stack{
char ch;
struct Stack* next;
}Stack;
typedef struct Linkstack{
Stack* top;
}Linkstack;
using namespace std;
int Isempty(Linkstack*); //判栈空
int Push(Linkstack*,char); //入栈
char Pop(Linkstack*); //出栈
void Input(string&); //输入表达式
void Balance(string); //检查符号平衡
int main(void){
string fix;
Input(fix);
Balance(fix);
return 0;
}
int Isempty(Linkstack* p){
return p->top==nullptr;
}
int Push(Linkstack* p,char ch){
Stack* s=new Stack;
s->ch=ch;
s->next=p->top;
p->top=s;
return 1;
}
char Pop(Linkstack* p){
if(Isempty(p)){
cout<<"The stack is empty"<<endl;
return 0;
}
Stack* temp=p->top;
char x=temp->ch;
p->top=temp->next;
delete(temp);
return x;
}
void Input(string& fix){
cout<<"Please input a fix."<<endl;
getline(cin,fix);
}
void Balance(string fix){
Linkstack p;
int i;
char temp;
for(i=0;i<fix.size();i++){
if(fix[i]=='(') Push(&p,fix[i]);
else if(fix[i]=='[') Push(&p,fix[i]);
else if(fix[i]=='{') Push(&p,fix[i]);
else if(fix[i]==')'){
temp=Pop(&p);
if(temp!='('){
cout<<"The fix is not balance."<<endl;
return;
}
}else if(fix[i]==']'){
temp=Pop(&p);
if(temp!='['){
cout<<"The fix is not balance."<<endl;
return;
}
}else if(fix[i]=='}'){
temp=Pop(&p);
if(temp!='{'){
cout<<"The fix is not balance."<<endl;
return;
}
}
}
if(Isempty(&p)) cout<<"The fix is balance."<<endl;
else cout<<"The fix is not balance."<<endl;
}
输出样例;
Please input a fix.
1=2--3043=1mc,.d32
The fix is balance.
Please input a fix.
(((((())))))
The fix is balance.
Please input a fix.
{0-d0[ njn(`2 e12),.c,w]midej}
The fix is balance.