forked from utkarsh006/LeetCode-Grind
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MAY 5_ Implement Stack using Queues
53 lines (38 loc) · 1.03 KB
/
MAY 5_ Implement Stack using Queues
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
class MyStack {
public:
queue<int> q;
queue<int> p;
MyStack() {
}
void push(int x)
{
q.push(x);
}
int pop()
{
while(q.size()!=1)
{ // push all other elements in the other queue except the last one
p.push(q.front());
q.pop();
}
int y = q.front();
q.pop(); // pop the last element but dont put it in other queue
while(p.size()!=0)
{
q.push(p.front()); // put all other elements back in first queue
p.pop();
}
return y;
}
int top()
{
int k = pop();
// top can be seen as just a pop function followed by a push
// pop gives last element and remove it from queue so if we put it back , we can get the functionality
q.push(k);
return k;
}
bool empty() {
return q.size()==0;
}
};