输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序。为了简单起见,我们假设push序列的任意两个整数都是不相等的。比如输入的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序列。

 

这题可以利用一个辅助栈来实现,过程很简单,但描述起来会有一些困难,所以直接代码了。

 

#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};
cout<<isStackPushPop(a, b, 5)<<endl;
return 0;
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
  • 2022-12-23
猜你喜欢
  • 2021-11-24
  • 2021-09-25
  • 2021-10-22
  • 2022-01-12
  • 2022-12-23
相关资源
相似解决方案