zoukankan      html  css  js  c++  java
  • 中缀表达式转后缀表达式

    中缀表达式转后缀表达式对于计算机专业的学生来说几乎是要人人掌握的,不过要把其中的脉络理清楚,对于编程能力一般的童鞋来说,还是有点小难度的。

    先贴一个地址,http://pal.cndev.org/2005/10/13/44016/,这篇文章对于中缀转后缀的算法讲解的还算比较清楚了。

    再贴代码,这是利用STL中的stack来实现的。

    #include <iostream>
    #include <stack>
    using namespace std;
    
    int main()
    {
    	string infix_exp;
    	cin>>infix_exp;
    	int len = infix_exp.length();
    	stack<char> oper;
    	for(int i = 0; i < len; i++)
    	{
    		char ch = infix_exp[i];
    		if(ch < '9' && ch > '0')
    			cout<<ch;
    		if(ch == '+' || ch == '-')
    		{
    			if(oper.empty() || oper.top() == '(')
    				oper.push(ch);
    			else{
    				cout << oper.top();
    				oper.pop();
    				oper.push(ch);
    			}
    		}
    		if(ch == '*' || ch == '/')
    		{
    			if(oper.empty() || oper.top() == '(' || oper.top() == '+' || oper.top() == '-')
    				oper.push(ch);
    			else{
    				cout << oper.top();
    				oper.pop();
    				oper.push(ch);
    			}
    		}
    		if(ch == '(')
    			oper.push(ch);
    		if(ch == ')')
    		{
    			for(;;)
    			{
    				if(oper.top() == '(')
    				{
    					oper.pop();
    					break;
    				}
    				else{
    					cout << oper.top();
    					oper.pop();
    				}
    			}
    		}
    	}
    	while(!oper.empty())
    	{
    		cout << oper.top();
    		oper.pop();
    	}
    	cout << endl;
    }
    

      

  • 相关阅读:
    C++细节3
    C++细节2
    C++细节1
    连通域标记方法
    dll动态链接库入门2
    UnixShell编程(第三版)
    Xcode 快捷键
    mysql在linux上的一点操作
    mysql 语句
    开机自动启动
  • 原文地址:https://www.cnblogs.com/findingsea/p/2447160.html
Copyright © 2011-2022 走看看