面试题31:栈的压入、弹出序列
题目
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
考点
栈模拟
书本版本
#include<stdio.h>
#include<string.h>
#define ERRCODE 0
bool IsPopOrder(const int *pPush, const int *pPop, int length)
{
if(pPush == nullptr || pPop == nullptr || length <= 0) return false;
int *temp = new int[length];
memset(temp,ERRCODE,length);
int tempIdx = 0, pushIdx = 0, popIdx = 0;
while (true)
{
if(tempIdx == 0){
while(pPush[pushIdx] != pPop[popIdx]){
temp[tempIdx++] = pPush[pushIdx++];
if(pushIdx == length) return false;
}
temp[tempIdx] = pPush[pushIdx];
}
if(temp[tempIdx] == pPop[popIdx]){
temp[tempIdx] = ERRCODE;
tempIdx --;
popIdx ++;
if(tempIdx == -1 && popIdx == length) return true;
continue;
}
if(temp[tempIdx] != pPop[popIdx]){
if(++pushIdx == length) return false;
while(pPush[pushIdx] != pPop[popIdx]){
temp[++tempIdx] = pPush[pushIdx++];
if(pushIdx == length) return false;
}
}
}
}
LeetCode版本(推荐)
class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
stack<int> temp;
int popidx =0;
for(auto num: pushed){
temp.push(num);
while(!temp.empty() && temp.top() == popped[popidx]){
popidx ++;
temp.pop();
}
}
return temp.empty();
}
};