-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path225_Implement_Stack_using_Queues.cc
66 lines (61 loc) · 1.41 KB
/
225_Implement_Stack_using_Queues.cc
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
class Stack {
public:
queue<int> main;
queue<int> temp;
// Push element x onto stack.
void push(int x) {
main.push(x);
}
// Removes the element on top of the stack.
void pop() {
if(!main.empty()){
while(main.size()>1){
int x=main.front();
main.pop();
temp.push(x);
}
main.pop();
}
else{
int s=temp.size();
int i=0;
while(i<s-1){
int x=temp.front();
temp.pop();
temp.push(x);
i++;
}
temp.pop();
}
}
// Get the top element.
int top() {
if(!main.empty()){
while(main.size()>1){
int x=main.front();
main.pop();
temp.push(x);
}
return main.front();
}
else{
int s=temp.size();
int i=0;
while(i<s-1){
int x=temp.front();
temp.pop();
temp.push(x);
i++;
}
int y=temp.front();
temp.pop();
temp.push(y);
return y;
}
}
// Return whether the stack is empty.
bool empty() {
if(main.empty() && temp.empty()) return true;
else return false;
}
};