-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue_using_Two_Stacks.cpp
74 lines (66 loc) · 1.46 KB
/
Queue_using_Two_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
/**
* Title : Queue using Two Stacks
* Author : Tridib Samanta
* Created : 18-05-2020
* Link : https://www.hackerrank.com/challenges/queue-using-two-stacks/problem
**/
#include<bits/stdc++.h>
using namespace std;
stack<long int> S1, S2;
void enqueue(int x) {
S1.push(x);
}
int dequeue() {
if (S2.empty() && S1.empty())
return -1;
if (S2.empty()) {
while (!S1.empty()) {
S2.push(S1.top());
S1.pop();
}
}
int element = S2.top();
S2.pop();
return element;
}
int printFront() {
if (S2.empty() && S1.empty())
return -1;
if (S2.empty()) {
while (!S1.empty()) {
S2.push(S1.top());
S1.pop();
}
}
return S2.top();
}
int main() {
int q;
cin >> q;
while (q--) {
int type;
cin >> type;
switch(type) {
case 1: {
int element;
cin >> element;
enqueue(element);
break;
}
case 2: {
int element;
element = dequeue();
break;
}
case 3: {
int element;
element = printFront();
cout << element << '\n';
}
default :
// Do nothing
break;
}
}
return 0;
}