比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。因为可以有如下的push和pop序列:push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,这样得到的pop序列就是4、5、3、2、1。但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。
分析:这到题除了考查对栈这一基本数据结构的理解,还能考查我们的分析能力。具体的实现代码如下:
// isStackPushPop.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;
bool isStackPushPop(int a[], int b[], int n)
{
stack<int> ms;
int i = -1, j = 0;
while (i < n && j < n)
{
if (ms.empty() || ms.top() != b[j])
ms.push(a[++i]);
else
{
ms.pop();
j ++;
}
}
return ms.empty();
}
int main()
{
int a[] = {1,2,3,4,5};
int b[] = {5,4,2,3,1};
//int b[]={4,5,3,2,1};
//int b[]={5,4,3,2,1};
cout<<isStackPushPop(a, b, 5)<<endl;
system("pause");
return 0;
}
// isStackPushPop.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;
bool isStackPushPop(int a[], int b[], int n)
{
stack<int> ms;
int i = -1, j = 0;
while (i < n && j < n)
{
if (ms.empty() || ms.top() != b[j])
ms.push(a[++i]);
else
{
ms.pop();
j ++;
}
}
return ms.empty();
}
int main()
{
int a[] = {1,2,3,4,5};
int b[] = {5,4,2,3,1};
//int b[]={4,5,3,2,1};
//int b[]={5,4,3,2,1};
cout<<isStackPushPop(a, b, 5)<<endl;
system("pause");
return 0;
}