使用栈实现后缀表达式计算

题目要求:使用栈实现后缀表达式计算,其中,在后缀表达式中,输入的数字为整数,且为正数,数字、符号之间用空格隔开,整个后缀表达式用“#”表示结束。

输入样例:

11 2 3 + *#

输出样例:

55


代码实现:

//通过栈 实现后缀表达式求值
#include <iostream>
using namespace std;

int top=-1;	//栈顶值
//类定义
class stack	
{
private:
	int number;
	stack* next;
public:
	stack()		//构造函数
	{ 
		number = 0;
		next = NULL;
	}
	~stack()	//析构函数
	{
		number = 0;
		delete next;
		next = NULL;
	}
	void push();	//入栈函数
	void push(int);	//有参入栈函数
	void pop(int &);//出栈函数
	void output();	//输出
	void real_input();	//后缀表达式输入
};

void stack::push()	//入栈函数
{
	stack* c1;
	c1 = next;
	next = new stack;
	next->next = c1;
	cin >> next->number;
	top++;
}

void stack::push(int temp) // 有参入栈函数
{
	stack* c1;
	c1 = next;
	next = new stack;
	next->next = c1;
	next->number=temp;
	top++;
}


void stack::pop(int& temp)	//出栈函数
{
	stack* c2 ;
	c2= next;
	while (c2 != NULL)
	{
	temp = next->number;
	next = next->next;
	c2->next = NULL;
	delete c2;
	c2 = NULL;
	top--;
	}
}

void stack::output()	//输出
{
	stack* temp;
	temp = next;
	while (temp != NULL)
	{
		cout << temp->number<<" ";
		temp = temp->next;
	}
}

void stack::real_input()	//后缀表达式输入
{
	push();
	while (cin.get() != '#') 
	{	
		char temp1 = cin.get();	
		int temp2, temp3;
		switch (temp1)
		{
		case '+': pop(temp2); pop(temp3); push(temp2 + temp3); break;
		case '-': pop(temp2); pop(temp3); push(temp3 - temp2); break;
		case '*': pop(temp2); pop(temp3); push(temp2 * temp3); break;
		case '/': pop(temp2); pop(temp3); push(temp3 / temp2); break;
		default:  cin.putback(temp1); push();
		}				
	}
}

int main()
{
	cout << "输入后缀表达式\n";
	stack s1;
	s1.real_input();
	cout << "结果\n";
	s1.output();

	return 0;
 }

注:本文仅供本人记录学习之用,多有瑕疵,请友好讨论。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值