Implement Queue using Stacks LeetCode solution in C++

1
class MyQueue {
2
public:
3
stack<int> s1;
4
stack<int> s2;
5

6
MyQueue() {}
7

8
void push(int x) {
9
s1.push(x);
10
}
11

12
int pop() {
13
if (s1.empty() && s2.empty()) return -1;
14
while (s2.empty()) {
15
while (!s1.empty()) {
16
s2.push(s1.top());
17
s1.pop();
18
}
19
}
20
int x = s2.top();
21
s2.pop();
22
return x;
23
}
24

25
int peek() {
26
if (!s2.empty()) {
27
return s2.top();
28
} else {
29
while (!s1.empty()) {
30
int val = s1.top();
31
s2.push(val);
32
s1.pop();
33
}
34
return s2.top();
35
}
36
}
37

38
bool empty() {
39
if (s1.empty() && s2.empty()) {
40
return true;
41
}
42
return false;
43
}
44
};
45

46
/**
47
* Your MyQueue object will be instantiated and called as such:
48
* MyQueue* obj = new MyQueue();
49
* obj->push(x);
50
* int param_2 = obj->pop();
51
* int param_3 = obj->peek();
52
* bool param_4 = obj->empty();
53
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0