【劍指offer】棧的壓入彈出序列

來源:互聯網
上載者:User

轉載請註明出處:http://blog.csdn.net/ns_code/article/details/26077863


    劍指offer上的第22題,九度OJ上AC。

題目描述:

輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。

輸入:

每個測試案例包括3行:

第一行為1個整數n(1<=n<=100000),表示序列的長度。

第二行包含n個整數,表示棧的壓入順序。

第三行包含n個整數,表示棧的彈出順序。

輸出:

對應每個測試案例,如果第二個序列是第一個序列的彈出序列輸出Yes,否則輸出No。

範例輸入:
5
1 2 3 4 5
4 5 3 2 1
5
1 2 3 4 5
4 3 5 1 2
範例輸出:
Yes
No

    判定方法如下:

    如果第二個序列中當前要判斷的元素剛好與棧頂元素相等,則直接pop出來,如果不等,則將第一個序列的後面還沒有入棧的元素入棧,直到將與之相等的元素入棧為止,如果第一個序列的所有的元素都入棧了,還沒有找到與之相等的元素,則說明第二個序列不是第一個序列的彈出序列,

    AC代碼如下:

/*本程式採用數組類比棧*/typedef int ElemType;#define MAX 100000 //棧的深度#include<stdio.h>#include<stdlib.h>#include<stdbool.h>int top = -1;/*在棧頂索引指標為top時,向棧A中壓入資料data*/bool push(int *A,ElemType data){if(top>=MAX-1 || top<-1)return false;A[++top] = data;return true;}/*在棧頂索引指標為top時,出棧*/bool pop(){if(top<0)return false;top--;return true;}/*判斷popList是否是pushList的彈出序列*/bool IsPopOrder(int *pushList,int *popList,int len,int *stack){if(popList==NULL || pushList==NULL || len<1)return false;int i;int pushIndex = 0;for(i=0;i<len;i++){while(top==-1 || stack[top] != popList[i]){//如果沒有元素可以push了,就說明不符合if(pushIndex == len)return false;push(stack,pushList[pushIndex++]);}pop();}return true;}int main(){int n;int stack[MAX]; //輔助棧while(scanf("%d",&n) != EOF){int *pushList = (int *)malloc(n*sizeof(int));if(pushList == NULL)exit(EXIT_FAILURE);int i;for(i=0;i<n;i++)scanf("%d",pushList+i);int *popList = (int *)malloc(n*sizeof(int));if(popList == NULL)exit(EXIT_FAILURE);for(i=0;i<n;i++)scanf("%d",popList+i);if(IsPopOrder(pushList,popList,n,stack))printf("Yes\n");elseprintf("No\n");free(pushList);pushList = NULL;free(popList);popList = NULL;}return 0;}

/**************************************************************      Problem: 1366      User: mmc_maodun      Language: C      Result: Accepted      Time:210 ms      Memory:2012 kb ****************************************************************/


聯繫我們

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