关于链栈的问题
我尝试了直接声明一个结点指针来指向栈顶,但是我忽略了函数形参是值传递,就算是指针也是值传递,故用到了二级指针作为函数参数
int Push(Linkstack **top,double x){
Linkstack *s=new Linkstack;
s->data=x;
s->next=*top;
//top=&s; 之前的错误写法
*top=s;
return 1;
}
之前的错误写法将新开辟的结点地址赋给指向原指针的指针,只是使得指向原指针的指针指向新开辟的指针,并没有改变原指针的指向
double Pop(Linkstack** top){
if(Isempty(*top)){
cout<<"The stack is empty"<<endl;
return 0;
}
Linkstack *temp=*top;
double x=temp->data;
//top=&(temp->next) 之前的错误写法
*top=temp->next;
free(temp);
return x;
}
Pop函数同样的问题
修改后的函数整体代码:
#include<iostream>
#include<string>
typedef struct Stack{
double data;
struct Stack* next;
}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*top){
return top==nullptr;
}
int Push(Linkstack **top,double x){
Linkstack *s=new Linkstack;
s->data=x;
s->next=*top;
*top=s;
return 1;
}
double Pop(Linkstack** top){
if(Isempty(*top)){
cout<<"The stack is empty"<<endl;
return 0;
}
Linkstack *temp=*top;
double x=temp->data;
*top=temp->next;
free(temp);
return x;
}
void Input(string& postfix){
cout<<"请输入一个后缀表达式"<<endl;
getline(cin,postfix);
}
double Calculate(string postfix){
string temp;
Linkstack *top=nullptr;
double temp1,temp2,temp3,sum;
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(&top,temp3);
temp.erase(0);
}else if(postfix[i]=='+'){
temp1=Pop(&top);
temp2=Pop(&top);
sum=temp1+temp2;
Push(&top,sum);
}else if(postfix[i]=='-'){
temp1=Pop(&top);
temp2=Pop(&top);
sum=temp1-temp2;
Push(&top,sum);
}else if(postfix[i]=='*'){
temp1=Pop(&top);
temp2=Pop(&top);
sum=temp1*temp2;
Push(&top,sum);
}else if(postfix[i]=='/'){
temp1=Pop(&top);
temp2=Pop(&top);
sum=temp1/temp2;
Push(&top,sum);
}
}
sum=Pop(&top);
return sum;
}