jobdu 28 堆棧的使用

來源:互聯網
上載者:User
題目描述:

    堆棧是一種基本的資料結構。堆棧具有兩種基本操作方式,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;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.