您的位置:首页 > 其它

栈的压入弹出序列

2017-06-22 16:07 357 查看
题目描述:

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;

bool IsPopOrder(int *pPush, int *pPop, int nLength)
{
if (pPush == NULL || pPop == NULL || nLength <= 0)
{
return false;
}

stack<int> s;
s.push(pPush[0]);
int nPop_index = 0;
int nPush_index = 1;
while (nPop_index < nLength)
{
while (s.top() != pPop[nPop_index] && nPush_index < nLength)
{
s.push(pPush[nPush_index]);
nPush_index++;
}

if (s.top() == pPop[nPop_index])
{
s.pop();
nPop_index++;
}
else
{
return false;
}
}

return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
int nPush[5] = {1,2,3,4,5};
int nPop1[5] = {4,5,3,2,1};
int nPop2[5] = {4,3,5,1,2};
int nPop3[5] = {5,4,3,2,1};
int nPop4[5] = {4,5,2,3,1};
cout << IsPopOrder(nPush, nPop1, 5) << endl;
cout << IsPopOrder(nPush, nPop2, 5) << endl;
cout << IsPopOrder(nPush, nPop3, 5) << endl;
cout << IsPopOrder(nPush, nPop4, 5) << endl;
system("pause");
return 0;
}


另一个思路:

class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
vector<int>temp;
int j = 0;
for(int i=0;i<pushV.size();)
{
temp.push_back(pushV[i++]);
while(j<popV.size()&&temp[temp.size()-1]==popV[j])
{
temp.pop_back();
++j;
}
}
return temp.empty();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: