表达式转为后缀表达式_后缀表达评估

表达式转为后缀表达式

Problem statement:

问题陈述:

Given a postfix expression, the task is to evaluate the expression and print the final value. Operators will only include the basic arithmetic operators like *, / , +, and -.

给定一个后缀表达式,任务是评估表达式并打印最终值。 运算符将仅包括基本算术运算符,例如*,/,+和-。

Infix expression: The expression of the form a op b. When an operator is in-between every pair of operands.

中缀表达式 :形式为op b的表达式。 当运算符位于每对操作数之间时。

Postfix expression: The expression of the form a b op. When an operator is followed for every pair of operands.

后缀表达式ab op形式的表达式。 每对操作数都遵循一个运算符时。

Input:

输入:

The first line of input contains an integer T denoting the number of test cases. The next T lines contain a postfix expression. The expression contains all characters and ^, *, /, +, -.

输入的第一行包含一个整数T,表示测试用例的数量。 接下来的T行包含一个后缀表达式。 该表达式包含所有字符以及^,*,/,+,-

Output:

输出:

For each test case, in a new line, evaluate the postfix expression and print the value.

对于每个测试用例,请在新行中评估后缀表达式并打印该值。

Examples:

例子:

    Input:	
    T = 1

    5641*+8-
    
    Output: 
    2

    Input:
    T = 1

    123+*8+
    
    Output: 
    13

Solution Approach

解决方法

Stack Based Approach

基于堆栈的方法

We will perform the following operation.

我们将执行以下操作。

Iterate from left to right, if we encounter operand then push it into the stack otherwise if we encounter operator then we will do the following,

从左到右迭代,如果遇到操作数,则将其压入堆栈;否则,如果遇到运算符,则将执行以下操作:

  • Pop top two elements from the stack, the first element is the second value of the integer (n2) and the second top element is the first value of the integer(n1) as stack follow last in first out manner.

    从堆栈中弹出顶部的两个元素,第一个元素是整数( n2 )的第二个值,第二个顶部元素是整数( n1 )的第一个值,因为堆栈以先进先出的方式跟随其后。

  • Then we will perform the operation represented by the operator like +, -, *, / etc.

    然后,我们将执行由运算符表示的操作,例如+,-,*,/等。

  • Then push the value calculated after performing the operation back into the stack.

    然后将执行该操作后计算出的值推回到堆栈中。

  • Finally, the stack contains only one value and that is the evaluated expression.

    最后,堆栈仅包含一个值,该值就是计算后的表达式。

Pseudo Code:

伪代码:

int infixvalue(string str):
{
	stack
   
   
    
     st; //declare stack.

	int n=str.length();  //string length

	//iterate from left to right
	for(int i=0;i<n;i++)
	{
		// if the character is not operator 
		// then push it into stack.
		if(str[i]!='+' and str[i]!='-' and str[i]!='*' and str[i]!='/')
		    st.push(str[i]-'0')
		else
		{
			int n2=st.top()	//get top of stack for second operand
			st.pop() 	//pop it from the stack.

			int n1=st.top()	//get top of stack for first operand
			st.pop()	//pop it from the stack.

			// if operator is encountered then 
			// perform the following operation.
			if(str[i]=='+') 
			    st.push(n1+n2)
			if(str[i]=='-')
			    st.push(n1-n2)
			if(str[i]=='*')
			    st.push(n1*n2)
			if(str[i]=='/')
			    st.push(n1/n2)
		}
	}
	// finally return the final result 
	// stored in the stack top.
	return st.top()
}

   
   
  • Time Complexity for above approach in worst case is: O(n)

    最坏情况下上述方法的时间复杂度为: O(n)

  • Space complexity for above approach is: O(n)

    上述方法的空间复杂度为: O(n)

C++ Implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int main()
{
    ll t;

    cout << "Enter number of test Cases: ";
    cin >> t;

    while (t--) {
        cout << "Enter postfix expression: ";
        string str;
        cin >> str;

        stack<ll> st; //declare stack.
        ll n = str.length(); //string length

        //iterate from left to right
        for (ll i = 0; i < n; i++) {
            // if the character is not operator then push it into stack.
            if (str[i] != '+' and str[i] != '-' and str[i] != '*' and str[i] != '/')
                st.push(str[i] - '0');
            else {
                int n2 = st.top(); //get top of stack for second operand
                st.pop(); //pop it from the stack
                int n1 = st.top(); //get top of stack for first operand
                st.pop(); //pop it from the stack.

                //if operator is encountered then perform the following operation.
                if (str[i] == '+')
                    st.push(n1 + n2);
                if (str[i] == '-')
                    st.push(n1 - n2);
                if (str[i] == '*')
                    st.push(n1 * n2);
                if (str[i] == '/')
                    st.push(n1 / n2);
            }
        }
        cout << "Final value: ";
        cout << st.top() << "\n";
    }
    
    return 0;
}

Output

输出量

Enter number of test Cases: 3
Enter postfix expression: 5641*+8-
Final value: 2
Enter postfix expression: 123+*8+
Final value: 13
Enter postfix expression: 562*-7+
Final value: 0


翻译自: https://www.includehelp.com/icp/postfix-expression-evaluation.aspx

表达式转为后缀表达式

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值