0%

225. 用队列实现栈

225. 用队列实现栈

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
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {

}

/** Push element x onto stack. */
// O(1)
void push(int x) {
if(!q1.empty())
q1.push(x);
else
q2.push(x);
}

/** Removes the element on top of the stack and returns that element. */
// O(n)
int pop() {
int ret;
if(!q1.empty())
{
while(q1.size() != 1)
{
q2.push(q1.front());
q1.pop();
}
ret = q1.front();
q1.pop();
}else
{
while(q2.size() != 1)
{
q1.push(q2.front());
q2.pop();
}
ret = q2.front();
q2.pop();
}
return ret;
}

/** Get the top element. */
// O(n)
int top() {
int ret;
if(!q1.empty())
{
while(q1.size() != 1)
{
q2.push(q1.front());
q1.pop();
}
ret = q1.front();
q2.push(q1.front());
q1.pop();
}else
{
while(q2.size() != 1)
{
q1.push(q2.front());
q2.pop();
}
ret = q2.front();
q1.push(q2.front());
q2.pop();
}
return ret;
}

/** Returns whether the stack is empty. */
bool empty() {
return q1.empty() && q2.empty();
}
private:
queue<int> q1;
queue<int> q2;
};

/**
* 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();
*/

另一种

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
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {

}

/** Push element x onto stack. */
// O(n)
void push(int x) {
q2.push(x);
while(!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
swap(q1, q2);
}

/** Removes the element on top of the stack and returns that element. */
// O(1)
int pop() {
auto ret = q1.front();
q1.pop();
return ret;
}

/** Get the top element. */
// O(1)
int top() {
return q1.front();
}

/** Returns whether the stack is empty. */
bool empty() {
return q1.empty();
}
private:
queue<int> q1;
queue<int> q2;
};

/**
* 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();
*/