題目描述:
堆棧是一種基本的資料結構。堆棧具有兩種基本操作方式,push 和 pop。Push一個值會將其壓入棧頂,而 pop 則會將棧頂的值彈出。現在我們就來驗證一下堆棧的使用。 輸入:
對於每組測試資料,第一行是一個正整數 n,0<n<=10000(n=0 結束)。而後的 n 行,每行的第一個字元可能是'P’或者'O’或者'A’;如果是'P’,後面還會跟著一個整數,表示把這個資料壓入堆棧;如果是'O’,表示將棧頂的值 pop 出來,如果堆棧中沒有元素時,忽略本次操作;如果是'A’,表示詢問當前棧頂的值,如果當時棧為空白,則輸出'E'。堆棧開始為空白。 輸出:
對於每組測試資料,根據其中的命令字元來處理堆棧;並對所有的'A’操作,輸出當時棧頂的值,每個佔據一行,如果當時棧為空白,則輸出'E’。當每組測試資料完成後,輸出一個空行。 範例輸入:
3AP 5A4P 3P 6O A0
範例輸出:
E53
code1:
#include <stdio.h>#include <string.h>#include <stack>using namespace std;int main(){int n,ps; //ps為跟在P之後需要push的數char c[10];while(scanf("%d",&n)!=EOF&&n!=0){stack<int> s; for(int i=0;i<n;i++) { scanf("%s",c); if(strcmp(c,"P")==0) { scanf("%d",&ps); s.push(ps); } else if(strcmp(c,"O")==0) { if(!s.empty()) s.pop(); } else if(strcmp(c,"A")==0) { if(s.empty()==true) printf("E\n"); else printf("%d\n",s.top()); } } printf("\n");}return 0;}
code2:
#include <stdio.h>#include <stack>#include <string.h>using namespace std;int main(){int n,ps;char c[10];while(scanf("%d",&n)!=EOF&&n!=0){stack<int> S;while(n--){scanf("%s",c);switch(c[0]){case 'P':scanf("%d",&ps);S.push(ps);break;case 'O':if(!S.empty())S.pop();break;case 'A':if(!S.empty())printf("%d\n",S.top());elseprintf("E\n");break;}}printf("\n");}return 0;}