24.栈的push和pop序列[StackPushPopSequence]

时间:2023-03-09 17:12:33
24.栈的push和pop序列[StackPushPopSequence]

【题目】

输入两个整数序列。其中一个序列表示栈的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序列。

【分析】

这到题除了考查对栈这一基本数据结构的理解,还能考查我们的分析能力。这道题的一个很直观的想法就是建立一个辅助栈,每次push的时候就把一个整数push进入这个辅助栈,同样需要pop的时候就把该栈的栈顶整数pop出来。

【代码】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
#include<iostream>
#include<stack>
using namespace std;

bool IsPossiblePopOrder(int push[], int pop[], int n)
{
    )
        return false;

;
    stack<int> mystack;
    while(p2 < n)
    {
        while(mystack.empty() || mystack.top() != pop[p2])
        {
            if(p1 < n)
                mystack.push(push[p1++]);
            else
                return false;
        }

while(!mystack.empty() && mystack.top() == pop[p2])
        {
            mystack.pop();
            p2++;
        }
    }
    return true;
}

void test_case()
{
    };
    };
    };
    int n = sizeof(push) / sizeof(int);
    cout << IsPossiblePopOrder(push, pop, n) << endl; // true
    cout << IsPossiblePopOrder(push, pop2, n) << endl; // false
}

【参考】

http://zhedahht.blog.163.com/blog/static/25411174200732102055385/

http://xingyunbaijunwei.blog.163.com/blog/static/765380672012330105813818/