-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyStack.cpp
More file actions
68 lines (57 loc) · 1.24 KB
/
MyStack.cpp
File metadata and controls
68 lines (57 loc) · 1.24 KB
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
class MyStack {
private:
queue<int> que;
public:
MyStack() {}
void push(int x) {
que.push(x);
for (int i = 0; i < que.size() - 1; i++) {
que.push(que.front());
que.pop();
}
}
int pop() {
int top = que.front();
que.pop();
return top;
}
int top() {
return que.front();
}
bool empty() {
return que.empty();
}
};
// 作者:richard-az
// 链接:https://leetcode-cn.com/problems/implement-stack-using-queues/solution/by-richard-az-1k2h/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class MyStack {
private:
queue<int> q1, q2;
public:
MyStack() {}
void transfer() {
while (q1.size() > 1) {
q2.push(q1.front());
q1.pop();
}
}
void push(int x) {
q1.push(x);
}
int pop() {
transfer();
int top = q1.front();
q1.pop();
swap(q1, q2);
return top;
}
int top() {
transfer();
return q1.front();
}
bool empty() {
return q1.empty() && q2.empty();
}
};