鬱悶的C小加(一)
- 描述
-
我們熟悉的表達式如a+b、a+b*(c+d)等都屬於中綴表達式。中綴表達式就是(對於雙目運算符來說)操作符在兩個操作數中間:num1 operand num2。同理,後綴表達式就是操作符在兩個操作數之後:num1 num2 operand。ACM隊的“C小加”正在鬱悶怎樣把一箇中綴表達式轉換爲後綴表達式,現在請你設計一個程序,幫助C小加把中綴表達式轉換成後綴表達式。爲簡化問題,操作數均爲個位數,操作符只有+-*/ 和小括號。
- 輸入
- 第一行輸入T,表示有T組測試數據(T<10)。
每組測試數據只有一行,是一個長度不超過1000的字符串,表示這個表達式。這個表達式裏只包含+-*/與小括號這幾種符號。其中小括號可以嵌套使用。數據保證輸入的操作數中不會出現負數。並且輸入數據不會出現不匹配現象。 - 輸出
- 每組輸出都單獨成行,輸出轉換的後綴表達式。
- 樣例輸入
-
2
-
1+2
-
(1+2)*3+4*5
- 樣例輸出
-
12+
-
12+3*45*+
-
#include<stdio.h> #include<stdlib.h> #include <string.h> #include<ctype.h> #include <stack> #define N 1000 using namespace std; stack<char> op;//定義保存運算符的棧 char s1[N],s2[N]; int priority(char ch)//定義運算符的優先級 { int num; switch(ch) { case '+': case '-':return 1; case '*': case '/':return 2; case '(': case ')':return 0; default:return -1; } } int main()//將中綴表達式轉換爲後綴表達式 { int T; scanf("%d",&T); op.push('#'); while(T--) { scanf("%s",s1); int len=strlen(s1); int top=-1; for(int i=0;i<len;i++) { if(isdigit(s1[i])) {//當是數字的時候 top++; s2[top]=s1[i]; } else if(s1[i]=='+'||s1[i]=='-'||s1[i]=='*'||s1[i]=='/') { //如果當前的操作符比棧頂的操作符優先級大的話,則將當前操作符進棧 if(priority(s1[i])>priority(op.top())) op.push(s1[i]); else { //當前運算符優先級小,則將棧中運算符優先級大於等於當前的都從棧出來 while(priority(op.top())>=priority(s1[i])) { top++; s2[top]=op.top();//將棧頂的運算符出棧 op.pop(); } op.push(s1[i]);//然後再把當前的運算符進棧 } } else if(s1[i]=='(') op.push(s1[i]); else if(s1[i]==')') { while(op.top()!='(') { top++; s2[top]=op.top(); op.pop(); } op.pop();//將左括號刪除 } } while(op.top()!='#')//如果此時符號棧仍不爲空則全部出棧 { top++; s2[top]=op.top(); op.pop(); } for(int i=0;i<=top;i++) { printf("%c",s2[i]); } printf("\n"); } return 0; }