-
Notifications
You must be signed in to change notification settings - Fork 0
/
implement_queue_using_stacks.cpp
97 lines (82 loc) · 2.04 KB
/
implement_queue_using_stacks.cpp
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
94
95
96
97
// https://leetcode.com/problems/implement-queue-using-stacks/
// June 08, 2016
#include <iostream>
#include <stack>
using namespace std;
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
stk_.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
stack<int> temp_stk;
// populate the elements of stk_ into temp_stk
while (!stk_.empty())
{
int x = stk_.top();
stk_.pop();
temp_stk.push(x);
}
// Now pop the top element from temp_stk
temp_stk.pop();
// Populate back the stack stk_
while (!temp_stk.empty())
{
int x = temp_stk.top();
temp_stk.pop();
stk_.push(x);
}
}
// Get the front element.
int peek(void) {
stack<int> temp_stk;
// populate the elements of stk_ into temp_stk
while (!stk_.empty())
{
int x = stk_.top();
stk_.pop();
temp_stk.push(x);
}
int front_element = temp_stk.top();
// Populate back the stack stk_
while (!temp_stk.empty())
{
int x = temp_stk.top();
temp_stk.pop();
stk_.push(x);
}
return front_element;
}
// Return whether the queue is empty.
bool empty(void) {
return stk_.empty();
}
private:
stack<int> stk_;
};
int main(int argc, char* argv[])
{
Queue q;
q.push(1);
q.push(2);
int front_element = q.peek();
cout << "peek: " << front_element << endl;
cout << "pop" << endl;
q.pop();
front_element = q.peek();
cout << "peek: " << front_element << endl;
cout << "now keep popping till queue becomes empty" << endl;
while (!q.empty())
{
front_element = q.peek();
cout << "peek: " << front_element << endl;
q.pop();
}
return 0;
}
/**
* Have a look at the two solutions:
* https://leetcode.com/articles/implement-queue-using-stacks/
*/