-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0232. Implement Queue using Stack.cpp
More file actions
73 lines (59 loc) · 1.13 KB
/
0232. Implement Queue using Stack.cpp
File metadata and controls
73 lines (59 loc) · 1.13 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
69
70
71
72
73
#include<iostream>
#include<stack>
class MyQueue {
public:
std::stack<int> st1, st2;
MyQueue() {
}
void push(int x) {
st1.push(x);
}
int pop() {
if (st2.empty()) {
while (st1.empty() == false) {
st2.push(st1.top());
st1.pop();
}
}
int x = st2.top();
st2.pop();
return x;
}
int peek() {
if (st2.empty()) {
while (!st1.empty()) {
st2.push(st1.top());
st1.pop();
}
}
return st2.top();
}
bool empty() {
return (st1.empty() && st2.empty());
}
};
int main() {
MyQueue q1;
q1.push(1);
q1.push(2);
q1.push(3);
q1.push(4);
q1.push(5);
while (!q1.empty()) {
std::cout << q1.peek() << " ";
q1.pop();
}
std::cout << std::endl;
MyQueue* q2 = new MyQueue();
q2->push(5);
q2->push(4);
q2->push(3);
q2->push(2);
q2->push(1);
while (!q2->empty()) {
std::cout << q2->peek() << " ";
q2->pop();
}
delete q2;
return 0;
}