利用树实现中缀表达式转为后缀表达式并计算结果

#include "stdafx.h"

#include<iostream>

#include<stack>

#include<queue>

#include<string>

using namespace std;

 

void HouZhui(string str, queue<char> &t)

{

int i = 0;

stack<char>s;//符号栈

cout << "后缀表达式:";

while (str[i] != '\0')

{

switch (str[i])

{

case '+':

s.push(str[i]);

break;

case '-':

s.push(str[i]);

break;

case '*':

s.push(str[i]);//遇到除了)之外的符号,直接入栈

break;

case '/':

s.push(str[i]);

break;

case '(':

s.push(str[i]);//注意:英文括号

break;

case ')'://遇到右括号:不进行入栈操作,直接执行出栈操作,并将出栈的元素输出,

while (s.top() != '(')//直到弹出栈的是左括号,括号不输出。

{

cout << s.top();

t.push(s.top());//入队

s.pop();

}

s.pop();//把原来符号栈中的左括号出栈

while (!s.empty()&&s.top()!='(')//弹出符号栈中,直到上一个(的全部符号

{

cout << s.top();

t.push(s.top());

s.pop();

}

break;

default://操作数直接输出

cout << str[i];

t.push(str[i]);//入队

}

i++;

}

while (!s.empty())//将符号栈全部出栈

{

cout << s.top();

t.push(s.top());//入队

s.pop();

}

cout << endl;

}

void JiSuan(queue<char>q)

{

//对存放后缀表达式的队列进行出队操作

//如果队头是操作数,压入操作数栈

//如果队头是操作符,从操作数栈弹出两个数,一次为numb2,numb1,进行相应计算,并将计算结果入栈

//重复以上操作,直到队为空。操作数栈中的数就是最终的计算结果

//(函数只考虑实现正确的表达式的计算)

//(函数的操作数只能是个位数)

//因为计算的表达式是以字符串的形式一次性输入的

stack<int>number;

int num1, num2;

while (!q.empty())

{

switch (q.front())

{

case '+':

num2 = number.top(); number.pop();

num1 = number.top(); number.pop();

num1 = num1 + num2;

number.push(num1);

break;

case'-':

num2 = number.top(); number.pop();

num1 = number.top(); number.pop();

num1 = num1 - num2;

number.push(num1);

break;

case'*':

num2 = number.top(); number.pop();

num1 = number.top(); number.pop();

num1 = num1 * num2;

number.push(num1);

break;

case'/':

num2 = number.top(); number.pop();

num1 = number.top(); number.pop();

num1 = num1 / num2;

number.push(num1);

break;

default:

number.push(q.front() - '0');

}

q.pop();

}

cout << "计算结果:" << number.top() << endl;

}

int main()

{

string str;//原中缀表达式

queue<char>s;//用一个队列存放后缀表达式

int i = 0;

while (1)

{

cout << "输入一个表达式:";

cin >> str;

HouZhui(str, s);

JiSuan(s);

}

return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_39514033/article/details/80412635