SDUT OJ 數據結構實驗之棧二:一般算術表達式轉換成後綴式

#include<iostream>
using namespace std;
int youxian(char s)
{
	if(s=='+'||s=='-') return 1;
	else if(s=='*'||s=='/') return 2;
	else if(s=='(')  return 3;
	else if(s==')')  return 4;
}
int main()
{
	int top=0;
	char s,b[110];
	while(cin>>s && s!='#')
	{
		if(s>='a' && s<='z')
			cout<<s;
		else
		{
			if(top==0)
			{
				b[top++]=s;
			}
			else
			{
				if(youxian(s)>youxian(b[top-1]))
				{
					if(youxian(s)==4)
					{
						while(b[top-1]!='(')
						{
							cout<<b[--top];
						}
						   top--;
					}
					else
					{
						b[top++]=s;
					}
				}
				else 
				{
					if(b[top-1]=='(')
					{
						b[top++]=s;
					}
					else
					{
						cout<<b[top-1];
						b[top-1]=s;
					}
				}
			}
		}
	}
	while(top!=0)
	{
		cout<<b[top-1];
		top--;
	}
	cout<<endl;
	return 0;			
}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章