用链栈计算逆波兰表达式
基本过程与顺序栈差不多
代码;
#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