-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathqueue_using_1_stack.cpp
More file actions
43 lines (39 loc) · 843 Bytes
/
queue_using_1_stack.cpp
File metadata and controls
43 lines (39 loc) · 843 Bytes
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
#include <iostream>
#include <stack>
using namespace std;
stack <int> st;
void enqueue() {
int val;
cin >> val;
st.push(val);
}
int dequeue() {
if (st.size() == 1) {
int val = st.top();
st.pop();
return val;
}
int curValue = st.top();
st.pop();
int rec = dequeue();
st.push(curValue);
return rec;
}
int main() {
string cmd;
for (int i = 0; i < 10; i++) {
cin >> cmd;
if (tolower(cmd[0]) == 'e') { // cmd == "enqueue"
enqueue();
}
else if (tolower(cmd[0]) == 'd') { // cmd == 'dequeue'
if (st.empty()) {
printf("Error: queue is empty\n");
exit(EXIT_FAILURE);
}
int val = dequeue();
printf("dequeued: %d\n", val);
}
}
return 0;
}