学习随记十二——用链栈计算逆波兰表达式

用链栈计算逆波兰表达式

基本过程与顺序栈差不多

代码;

#include<iostream>
#include<string>
typedef struct Stack{
	double data;
	struct Stack* next;
}Stack;
typedef struct Linkstack{
	struct Stack* top;
}Linkstack;
using namespace std;
int Isempty(Linkstack*);
int Push(Linkstack*,double);
double Pop(Linkstack*);
void Input(string&);
double Calculate(string);
int main(void){
	string postfix;
	Input(postfix);
	double sum;
	sum=Calculate(postfix);
	cout<<sum<<endl;
	return 0;
}
int Isempty(Linkstack*p){
	return p->top==nullptr;
}
int Push(Linkstack*p,double x){
	Stack*s=new Stack;
	s->data=x;
	s->next=p->top;
	p->top=s;
	return 1; 
}
double Pop(Linkstack* p){
	if(Isempty(p)){
		cout<<"The stack is empty"<<endl;
		return 0;
	}
	Stack*temp=p->top;
	double x=temp->data;
	p->top=temp->next;
	free(temp);
	return x; 
}
void Input(string& postfix){
	cout<<"请输入一个后缀表达式"<<endl;
	getline(cin,postfix);
} 
double Calculate(string postfix){
	string temp;
	Linkstack p;
	double temp1,temp2,temp3,sum;
	p.top=nullptr;
	int i;
	for(i=0;i<postfix.size();i++){
		if(isdigit(postfix[i])||postfix[i]=='.'){
			temp+=postfix[i];
		}else if(postfix[i]==' '){
			temp3=stod(temp);
			Push(&p,temp3);
			temp.erase(0);
		}else if(postfix[i]=='+'){
			temp1=Pop(&p);
			temp2=Pop(&p);
			sum=temp1+temp2;
			Push(&p,sum);
		}else if(postfix[i]=='-'){
			temp1=Pop(&p);
			temp2=Pop(&p);
			sum=temp2-temp1;
			Push(&p,sum);
		}else if(postfix[i]=='*'){
			temp1=Pop(&p);
			temp2=Pop(&p);
			sum=temp1*temp2;
			Push(&p,sum);
		}else if(postfix[i]=='/'){
			temp1=Pop(&p);
			temp2=Pop(&p);
			sum=temp2/temp1;
			Push(&p,sum);
		}
	} 
	sum=Pop(&p);
	return sum;
}
请输入一个后缀表达式
1 2 3 4 5 ++++
15

请输入一个后缀表达式
345 23.765 88.35 123.99 --*
4096.88
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值