-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22_StackPushPopOrder.cpp
More file actions
42 lines (38 loc) · 893 Bytes
/
Copy path22_StackPushPopOrder.cpp
File metadata and controls
42 lines (38 loc) · 893 Bytes
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
41
42
#include <iostream>
#include <stack>
using namespace std;
bool isPopOrder(const int* pPush, const int* pPop, int length)
{
if (pPush == NULL || pPop == NULL || length <= 0)
return false;
if (length <= 2)
return true;
stack<int> s;
int k = 0;
for (int i = 0; i < length; i++)
{
if (!s.empty() && s.top() == pPop[i])
{
s.pop();
continue;
}
while (k < length && pPush[k] != pPop[i])
{
s.push(pPush[k]);
k++;
}
if (k >= length)
return false;
k++;
}
return true;
}
int main()
{
int push1[] = {1, 2, 3, 4, 5};
int pop1[] = {4, 5, 3, 2, 1};
int pop2[] = {5, 3, 4, 2 ,1};
cout << boolalpha << isPopOrder(push1, pop1, 5) << endl;
cout << isPopOrder(push1, pop2, 5) << endl;
return 0;
}