輸入兩個整數序列。其中一個序列表示棧的push順序,判斷另一個序列有沒有可能是對應的pop順序
阿新 • • 發佈:2019-02-13
輸入兩個整數序列。其中一個序列表示棧的push 順序,判斷另一個序列有沒有可能是對應的pop 順序。
為了簡單起見,我們假設push 序列的任意兩個整數都是不相等的。
比如輸入的push 序列是1、2、3、4、5,那麼4、5、3、2、1 就有可能是一個pop 系列,但序列4、3、5、1、2 就不可能是push 序列1、2、3、4、5 的pop 序列。
思路:
1.首先新建一個棧模擬入棧入棧,都是在push序列中進行。
2.將push序列依次開始入棧,直到棧頂元素等於pop序列的第一個元素。
3.push的棧頂元素出棧,pop序列移到第二元素。
4.如果push棧頂繼續等於pop序列現在的元素,則繼續出棧並pop後移。
5.如果push已經全部入棧但是pop序列未遍歷結束,且棧頂元素不等於現在所指元素則返回false。
6.如果棧為空,且pop也已經遍歷結束,則返回true
按照上述思路,給出了原始碼:程式碼中有兩個實現,其中第一個是按照原作者的思路實現的,另外一個是網上的答案。
#include <iostream> #include <stack> using namespace std; bool isPopSerial(int push[], int pop[], int n)//原作者自己寫的一種方法,注意函式名 { int i=0,j=0; stack<int> mystack; while(i < n)//只要沒有全部將push陣列push到棧中 { mystack.push(push[i]); i++; while(!mystack.empty() && mystack.top() == pop[j]) { mystack.pop(); j++; } } if( mystack.empty() && j==n)//最後是pop序列的唯一條件:棧變空了,且pop序列遊標到了最後 return true; return false;//除此之外都不是pop序列 } bool isPopSeries(int push[],int pop[],int length)//網上流傳的經典答案 { if(!push||!pop||length<=0) return false; stack<int> temp; int pushNum=0; int i = 0; while(i < length) { while(temp.empty()||temp.top()!=pop[i]) { if(pushNum < length) temp.push(push[pushNum++]); else return false; } if(!temp.empty()&&temp.top()==pop[i]) { temp.pop(); i++; } } return true; } int main() { int pushArray[5] = {1,2,3,4,5}; int popArray[5] = {4,5,3,2,1}; if(isPopSerial(pushArray,popArray,5)) cout<<"yes"<<endl; else cout<<"no"<<endl; return 0; }