学习随记十五——关于链栈的问题

关于链栈的问题

我尝试了直接声明一个结点指针来指向栈顶,但是我忽略了函数形参是值传递,就算是指针也是值传递,故用到了二级指针作为函数参数

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;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值