-
Notifications
You must be signed in to change notification settings - Fork 0
/
Smallest_Element_at_Bottom.cpp
103 lines (89 loc) Β· 3.27 KB
/
Smallest_Element_at_Bottom.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
98
99
100
101
102
103
/* Write a C++ program to create a stack such that the smallest element always stays at the bottom (also, largest element always stays at the top) of the stack */
#include <iostream>
#include <stack>
using namespace std;
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
struct Queue{
stack<int> s1, s2;
void enQueue(int x){
// Move all elements from s1 to s2
while (!s1.empty() && x < s1.top()) { // IMPORTANT !
s2.push(s1.top());
s1.pop();
}
// Push item into s1
s1.push(x);
// Push everything back to s1
while (!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
cout << x << " β EnQueued Successfully\n";
}
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
// Dequeue an item from the queue
int deQueue(){
// if first stack is empty
if (s1.empty()) {
cout << "Queue is Empty";
exit(0);
}
// Return top of s1
int x = s1.top();
s1.pop();
cout << x << " β DeQueued Successfully\n";
return x;
}
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
void display(){
if (s1.empty()) {
cout << "Queue is Empty\n";
exit(0);
}
// Move all elements from s1 to s2
while (!s1.empty()) {
cout << s1.top() << endl;
s2.push(s1.top());
s1.pop();
}
// Push everything back to s1
while (!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
cout << endl;
}
};
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/
// Driver code
int main(){
Queue q;
int elem;
int num;
do{
cout << "Enter \n1 ββββ> push\n2 ββββ> pop\n3 ββββ> display\n4 ββββ> exit\n";
cout << "Please enter your choice : ";
cin >> num;
switch(num){
case 1:
cout << "\nEnter a Number : ";
cin >> elem;
q.enQueue(elem);
break;
case 2:
q.deQueue();
break;
case 3:
cout << endl;
q.display();
break;
case 4:
break;
default :
cout << "Invalid Choice\n";
}
cout << endl;
}while(num != 4);
return 0;
}
/*βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ*/