剑指Offer之 - 栈的压入、弹出序列
2015-05-07 14:26
525 查看
题目:
输入两个整数序列,第一个表示压入顺序,判断第二个序列是否是该栈的弹出序列。比如:压入序列1,2,3,4,5,则序列4,5,3,2,1是弹出序列,但是序列4,3,5,1,2就不可能是弹出序列。
思路:
把第一个序列的数入栈,直到遇到可第二个序列的数相等。如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。否则入栈,比如1 != 4 ,则把1入栈。直到4 == 弹出的数字4
如果所有的数字都压入栈了仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列
代码:
#include<iostream>#include <stack>
using namespace std;
//功能:已知栈的压入序列,判断一个序列是否是弹出序列
//比如:压入序列1,2,3,4,5,则序列4,5,3,2,1是弹出序列,但是序列4,3,5,1,2就不可能是弹出序列
//思路:如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。否则入栈,比如1 != 4 ,则把1入栈。直到4 == 弹出的数字4
//如果所有的数字都压入栈了仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列
bool IsPopOrder(const int *pPush , const int * pPop , int nLength)
{
if(pPush == NULL || pPop == NULL || nLength <= 0)
return false;
const int *pNextPush = pPush;
const int *pNextPop = pPop;
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)
return true;
}
return false;
}
bool IsPopOrderMy(const int *pPush , const int * pPop , int nLength)
{
if(pPush == NULL || pPop == NULL || nLength <= 0)
return false;
int i = 0 , j = 0;//i是入栈下标,j是出栈下标
stack<int> s;
while(j < nLength)
{
while(s.empty() || s.top() != pPop[j])
{
if(i == nLength)
break;
s.push(pPush[i]);
i++;
}
if(s.top() != pPop[j])
return false;
s.pop();
j++;
}
if(s.empty() && j == nLength)
return true;
else
return false;
}
int main()
{
int a[] = {1,2,3,4,5};
int b[] = {4,5,3,2,1};
cout<<IsPopOrderMy(a , b , 5)<<endl;
return 0;
}
相关文章推荐
- 剑指offer-题22:栈的压入、弹出序列
- 剑指offer代码解析——面试题22栈的压入、弹出序列
- 【剑指offer】面试题22:栈的压入弹出序列
- 【剑指offer】栈的压入、弹出序列(java版)
- 剑指offer第二十一题【栈的压入、弹出序列】c++实现
- 剑指offer面试题22:栈的压入、弹出序列
- 剑指Offer - 九度1366 - 栈的压入、弹出序列
- 剑指Offer:面试题22——栈的压入,弹出序列(java实现)
- 剑指offer--栈的压入、弹出序列
- 剑指offer代码解析——面试题22栈的压入、弹出序列
- 剑指Offer: (Java实现) 栈的压入、弹出序列
- 剑指Offer-31:栈的压入、弹出序列
- 剑指offer22--栈的压入弹出序列
- 【剑指offer】面试题31:栈的压入、弹出序列
- (5)剑指Offer之栈变队列和栈的压入、弹出序列
- 剑指offer 栈的压入、弹出序列
- 牛客网-剑指offer-21-栈的压入、弹出序列
- 【剑指offer】题22:栈的压入、弹出序列
- 剑指offer: 栈的压入、弹出序列
- 剑指Offer-面试题22 栈的压入、弹出序列(python实现)