轉載請註明出處: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
****************************************************************/