C++ 中缀转后缀并求值

## 1.中缀转后缀算法思想

 遍历字符串:
   一.若为数字1~9,进入后缀队列;
   二.若为左括号‘(’,进入符号栈;
   三.若为右括号’)‘,将栈顶元素压入后缀队列,直到栈顶为’(‘;
   四.若为‘+’,‘-‘,当栈不为空时,将栈顶元素压入后缀队列,直到栈顶为’(‘;
   五.若为’*‘,’\‘,当栈不为空且栈顶元素不为’+‘,’-‘时,将栈顶元素压入后缀队列,直到栈顶为’(‘。
 遍历结束时,若栈不为空,将栈内元素压入后缀队列。   

2.后缀表达式求值算法思想

 遍历后缀表达式:
   一.若为数字1~9,进入数据栈;
   二.若为运算符:’+‘,’-‘,’*‘,’/‘,取出数据栈顶两个元素进行运算,结果压栈
   三.输出栈顶元素。

运行代码

// test0304.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;

#include<stack>
#include<queue>
int transform_calculate(char* c);

int _tmain(int argc, _TCHAR* argv[])
{
	char c1[]={"((1+2)*(3+4))"};
	transform_calculate(c1);
	char c2[]="(((1+2)*3-4)/5)";
	transform_calculate(c2);
	system("pause");
	return 0;
}
int transform_calculate(char* c)
{
	stack<char> s;
	stack<int> s1;
	queue<char> q;
	cout<<"中缀表达式:";
	for (int i = 0; i < strlen(c); i++)
	{
		cout<<c[i]<<" ";
	}
	cout<<endl;
	for(int i=0;i<strlen(c);i++)
	{
		if(c[i]>'0'&&c[i]<='9')
			q.push(c[i]);
		else if(c[i]=='(')
			s.push(c[i]);
		else if(c[i]==')')
		{
			while(s.top()!='(')
			{
				q.push(s.top());
				s.pop();
			}
			s.pop();
		}
		else if(c[i]=='+'||c[i]=='-')
		{
			while(s.top()!='(')
			{
				if(!s.empty())
			    {
			    	q.push(s.top());
				    s.pop();
		    	}
			}
			s.push(c[i]);
		}
		else if(c[i]=='*'||c[i]=='/')
		{
			while(s.top()!='('&&s.top()!='+'&&s.top()!='-')
			{
				if(!s.empty())
				{
					q.push(s.top());
					s.pop();
				}
			}
			s.push(c[i]);
		}
	}
	while(!s.empty())
	{
		q.push(s.top());
		s.pop();
	}
	cout<<"后缀表达式:";
	queue<char> p=q;
	while(!p.empty())
	{
		cout<<p.front()<<" ";
		p.pop();
	}
	cout<<endl;
	while(!q.empty())
	{
		if(q.front()>'0'&&q.front()<='9')
		{
			s1.push(q.front()-'0');
			q.pop();		    
		}
		else if(q.front()=='+')
		{
			int i=s1.top();
			s1.pop();
			int j=s1.top();
			s1.pop();
			s1.push(j+i);
			q.pop();
		}
		else if(q.front()=='-')
		{
			int i=s1.top();
			s1.pop();
			int j=s1.top();
			s1.pop();
			s1.push(j-i);
			q.pop();
		}
		else if(q.front()=='*')
		{
			int i=s1.top();
			s1.pop();
			int j=s1.top();
			s1.pop();
			s1.push(j*i);
			q.pop();
		}
		else if(q.front()=='/')
		{
			int i=s1.top();
			s1.pop();
			int j=s1.top();
			s1.pop();
			s1.push(j/i);
			q.pop();
		}
	}
	cout<<"计算结果:";
	while(!s1.empty())
	{
		cout<<s1.top();
		s1.pop();
	}
	cout<<endl<<endl;
	return true;
}

运行结果

在这里插入图片描述

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值