zoukankan      html  css  js  c++  java
  • Infix to posfix 自己写stack,没有()

    #include<iostream>
    #include<string>
    using namespace std;
    
    template<typename Type>
    struct Node
    {
    	Type data;
    	Node<Type>*next;
    };
    
    template<typename Type>
    class Stack
    {
    private:
    	Node<Type>*head;
    public:
    	//构造函数
    	Stack()
    	{
    		head = new Node<Type>;
    		head->next = NULL;
    	}
    	//析构函数	 
    	~Stack()
    	{
    		delete head;
    	}
    	//判空
    	bool isEmpty()
    	{
    		if (head->next == NULL)
    			return true;
    		return false;
    	}
    
    	//入栈
    	void push(Type item)
    	{
    		Node<Type>*p = new Node<Type>;
    		p->data = item;
    		p->next = head;
    		head = p;
    	}
    
    	//出栈	 
    	void pop()
    	{
    		if (isEmpty())
    			return;
    		else
    		{
    			Node<Type>*p = head;
    			head = p->next;
    			delete p;
    		}
    	}
    
    	//取栈顶
    	char top()
    	{
    		return head->data;
    	}
    };
    
    //优先级判断
    char compare(char opt, char si)
    {
    	if ((opt == '+' || opt == '-') && (si == '*' || si == '/'))
    		return '<';
    	else if (opt == '#')
    		return '<';
    	return '>';
    }
    
    //判断是否为运算符
    bool isOp(char c)
    {
    	if (c == '+' || c == '-' || c == '*' || c == '/')
    		return true;
    	return false;
    }
    
    int main()
    {
    	Stack<char>op;
    	Stack<char>num;
    	op.push('#');
    	num.push('#');
    
    	string s;
    	cin >> s;
    
    	for (int i = 0; i<s.size(); i++)
    	{
    		if (!isOp(s[i]))
    			num.push(s[i]);
    		else
    		{
    			char c = compare(op.top(), s[i]);
    			if (c == '<')
    				op.push(s[i]);
    			else
    			{
    				num.push(op.top());
    				op.pop();
    				op.push(s[i]);
    			}
    		}
    	}
    
    	while (op.top() != '#')
    	{
    		num.push(op.top());
    		op.pop();
    	}
    
    	string s1 = "";
    
    	while (num.top() != '#')
    	{
    		s1 = s1 + num.top();
    		num.pop();
    	}
    
    	for (int i = 0; i<s1.size() / 2; i++)
    	{
    		char temp = s1[i];
    		s1[i] = s1[s1.size() - 1 - i];
    		s1[s1.size() - 1 - i] = temp;
    	}
    
    	cout << s1 << endl;
    
    	return 0;
    }
    

      

  • 相关阅读:
    史上最全的maven pom.xml文件教程详解
    Java中的断言Assert
    Log4j详细配置
    (实战篇)SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)
    Java的反射机制
    mysql数据库常用SQL语句
    响应式布局——@media详解
    CXF使用教程(三)——基于Spring的webService开发
    CXF使用教程(二)——webService自动生成客户端代码
    Spring事务管理
  • 原文地址:https://www.cnblogs.com/KennyRom/p/5940652.html
Copyright © 2011-2022 走看看