255. 验证前序遍历序列二叉搜索树
为保证权益,题目请参考 255. 验证前序遍历序列二叉搜索树(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class MyStack
{
private:
queue<int> queues;
queue<int> queues_back;
public:
/** Initialize your data structure here. */
MyStack()
{
// Nothing
}
/** Push element x onto stack. */
void push(int x)
{
queues.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop()
{
int res = 0;
if (queues.empty())
{
res = -1;
}
else
{
for (int i = 1; i < queues.size(); ++i)
{
queues.push(queues.front());
queues.pop();
}
res = queues.front();
queues.pop();
}
return res;
}
/** Get the top element. */
int top()
{
int res = 0;
if (queues.empty())
{
res = -1;
}
else
{
for (int i = 1; i < queues.size(); ++i)
{
queues.push(queues.front());
queues.pop();
}
res = queues.front();
queues.push(queues.front());
queues.pop();
}
return res;
}
/** Returns whether the stack is empty. */
bool empty()
{
return queues.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
int main()
{
MyStack m;
m.push(1);
m.push(2);
cout << m.top() << endl;
cout << m.pop() << endl;
return 0;
}
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93