棧(裸題)

來源:互聯網
上載者:User

標籤:pop   contain   values   repeat   get   number   symbols   eof   jpg   

Stack    Aizu - ALDS1_3_A

Write a program which reads an expression in the Reverse Polish notation and prints the computational result.

An expression in the Reverse Polish notation is calculated using a stack. To evaluate the expression, the program should read symbols in order. If the symbol is an operand, the corresponding value should be pushed into the stack. On the other hand, if the symbols is an operator, the program should pop two elements from the stack, perform the corresponding operations, then push the result in to the stack. The program should repeat this operations.

Input

An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.

You can assume that +, - and * are given as the operator and an operand is a positive integer less than 106

Output

Print the computational result in a line.

Constraints

2 ≤ the number of operands in the expression ≤ 100
1 ≤ the number of operators in the expression ≤ 99
-1 × 109 ≤ values in the stack ≤ 109

Sample Input 1
1 2 +
Sample Output 1
3
Sample Input 2
1 2 + 3 4 - *
Sample Output 2
-3
NotesTemplate in C


本題就是一個裸的棧問題,計算尾碼表答式,具體後追運算式是什麼就不清楚的講了,網上很多,只要知道從右往左一次遍曆,遇到一個符號就取出他的前兩個數來計算,因為還存在括弧這種情況所以會使用到棧。而My Code則是用數組類比棧,老實說我覺得STL的棧真的很慢。

簡單題不多說,直接上代碼:

 1     #include <iostream>   2     #include <cstdio>   3     #include <cstdlib>   4     #include <cstring>   5     using namespace std;   6        7     const int maxn = 100 + 5;   8        9     int top = 0;  10     int S[1000];  11       12     void push(int key){  13       S[++top] = key;  14       return;  15     }  16       17     int pop(){  18       top--;  19       return S[top+1];  20     }  21       22     int main(){  23       int a,b;  24       top = 0;  25       char s[maxn];  26       while(scanf("%s",s) != EOF){  27         if(s[0] == ‘+‘){  28           a = pop();  29           b = pop();  30           push(a+b);  31         }  32         else if(s[0] == ‘-‘){  33           b = pop();  34           a = pop();  35           push(a-b);  36         }  37         else if(s[0] == ‘*‘){  38           a = pop();  39           b = pop();  40           push(a*b);  41         }  42         else{  43           push(atoi(s));  44         }  45       }  46       printf("%d\n",pop());  47     }  

 

棧(裸題)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.