您的位置:首页 > Web前端

剑指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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: