forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Efficient_Enqueue.cpp
81 lines (68 loc) · 1.52 KB
/
Efficient_Enqueue.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
#include <iostream>
#include <stack>
#include <queue>
#include <climits>
using namespace std;
class Stack {
private:
queue<int> q1, q2;
public:
// Push element x onto stack.
void push(int x) {
q1.push(x);
}
// Removes the element on top of the stack.
int pop() {
if (q1.empty()) {
cout << "Stack is empty!";
return INT_MIN;
}
int last;
if (q1.size() != 1) {
int size = q1.size();
for (int i = 0; i < size-1; i++) {
q2.push(q1.front());
q1.pop();
}
last = q1.front();
q1.pop();
swap(q1, q2);
}
return last;
}
// Get the top element.
int top() {
return q1.front();
}
// Return whether the stack is empty.
bool empty() {
return q1.empty();
}
void printStack() {
if (q1.empty()) {
cout << "stack is empty!\n";
return;
}
queue<int> temp;
temp = q1;
while (temp.size()) {
cout << temp.front() << endl;
temp.pop();
}
}
};
int main() {
Stack push_efficient;
push_efficient.push(10);
push_efficient.push(20);
push_efficient.push(30);
push_efficient.push(40);
push_efficient.push(50);
push_efficient.pop();
push_efficient.push(60);
push_efficient.push(70);
push_efficient.pop();
push_efficient.push(80);
push_efficient.printStack();
return 0;
}