基于栈的应用之中缀转后缀

#include<iostream>
#include<string>
#include<map>
#include<utility>
#include<stack>
using namespace std;
void infix2postfix(const string &infix,string & postfix);
bool isParenLeft(char ch);
bool isParenRight(char ch);
bool isOperand(char ch);
bool isOperator(char ch);
bool priority(char ch1,char ch2);
typedef pair<char ,int> Pair;
map<char,int>opeMap;
int table[4][4]={{0,0,1,1},{0,0,1,1},{-1,-1,0,0},{0,0,-1,-1}};
int main()
{

	opeMap.insert(Pair('+',0));
        opeMap.insert(Pair('-',1));
	opeMap.insert(Pair('*',2));
	opeMap.insert(Pair('/',3));

	cout<<"enter the right infix expression :";
	string str1,str2;
	getline(cin,str1);
	cout<<" the infix expression is :"<<str1<<endl;
	cout<<"after converting ,the postfix expression is :";
	infix2postfix(str1,str2);
	cout<<str2<<endl;
	return 0;

}
bool priority(char ch1,char ch2)
{
	if(table[opeMap[ch1]][ch2]>=0)
		return true;
	else
		return false;

}
bool isParenLeft(char ch)
{
	return (ch=='['||ch=='{'||ch=='(');
}
bool isParenRight(char ch)
{
	return (ch==']'||ch=='}'||ch==')');
}
bool isOperand(char ch)
{
	return(ch>='a'&&ch<='z');
}
bool isOperator(char ch)
{
	return (ch=='+'||ch=='-'||ch=='/'||ch=='*');
}
void infix2postfix(const string &infix,string & postfix)
{
	int size=infix.size();

	char ch;
	stack<char> s;
	for(int i=0;i<size;i++)
	{
		ch=infix[i];
		if(isOperand(ch))
		{
			postfix=postfix+ch;
		}
		else if(isParenLeft(ch))
		{
                	s.push(ch);				
		}
		else if(isParenRight(ch))
		{
			ch=s.top();
			s.pop();
			while(!isParenLeft(ch))
			{
				postfix=postfix+ch;
				ch=s.top();
				s.pop();
			}
		}
		else if(isOperator(ch))
		{
			while(!s.empty()&&!isParenLeft(s.top())&&!priority(ch,s.top()))
			{
				postfix=postfix+s.top();
				s.pop();
			}
			s.push(ch);
		}
		
	}
	while(!s.empty())
	{
		postfix=postfix+s.top();
		s.pop();
	}
}

算法详解:

       1、在遇到操作数时,将其追加到输出字符串postfix中,在后缀表达式中,操作数的顺序与其在中缀表达式中的顺序相同,中缀表达式中操作符左边的操作数也出现在后缀表达式中的操作符的左边。

       2、使各个左括号符入栈。

       3、在遇到操作符时,若栈为空,则使操作符入栈。若栈非空,则使优先级更高(或相同)的操作符出栈,并追加到postfix中,在遇到左括号符,或优先级更低的操作符,或栈为空时停止。然后使新操作符入栈,这样,该步骤按优先级和从左到右的顺序给操作符排序。注意,使操作符持续出栈,直到

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值