题目要求:使用栈实现后缀表达式计算,其中,在后缀表达式中,输入的数字为整数,且为正数,数字、符号之间用空格隔开,整个后缀表达式用“#”表示结束。
输入样例:
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;
}
注:本文仅供本人记录学习之用,多有瑕疵,请友好讨论。

被折叠的 条评论
为什么被折叠?



