剑指offer--面试题22

时间:2023-03-10 03:57:12
剑指offer--面试题22

关键在于思路,  需要两个输入向量,而函数中需要一个辅助栈

思路:以待判出栈序列为基础,逐个判断它与栈顶元素是否相等,相等则弹出且j++,这表明此元素可为出栈顺序元素,不相等则栈元素不断入栈,直至相等,否则则判为非出栈序列!

#include<stack>

bool IsStackSquence(int* array1, int length1, int* array2, int length2)
{
bool IsOutStack = true;
if(array1 == NULL || length1 <= || array2 == NULL || length2 <= || length1 != length2)
return !IsOutStack; std::stack<int> st;
int i = ;
int j = ; st.push(array1[i++]); while(j < length2)
{
while(array2[j] != st.top() && i < length1)
{
st.push(array1[i]);
i++;
}
if(array2[j] != st.top() && i == length1)
return !IsOutStack; st.pop();
j++;
} return IsOutStack;
}

参考代码:

#include <stack>

bool IsPopOrder(const int* pPush, const int* pPop, int nLength)
{
bool bPossible = false; if(pPush != NULL && pPop != NULL && nLength > )
{
const int* pNextPush = pPush;
const int* pNextPop = pPop; std::stack<int> stackData; while(pNextPop - pPop < nLength)
{
// 当辅助栈的栈顶元素不是要弹出的元素
// 先压入一些数字入栈
while(stackData.empty() || stackData.top() != *pNextPop)
{
// 如果所有数字都压入辅助栈了,退出循环
if(pNextPush - pPush == nLength)
break; stackData.push(*pNextPush); pNextPush ++;
} if(stackData.top() != *pNextPop)
break; stackData.pop();
pNextPop ++;
} if(stackData.empty() && pNextPop - pPop == nLength)
bPossible = true;
} return bPossible;
}

学习:const int*