学习随记二十一——使用链栈完成平衡符号的检测(大,中,小括号)

使用链栈完成平衡符号的检测(大,中,小括号)

基本思路与使用顺序栈完成平衡符号的检测一样,不再赘述。
整体代码:

#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.
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值