-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_using_queue.cpp
82 lines (71 loc) · 1.13 KB
/
stack_using_queue.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
//stack using queue
//TC = O(n) SC = O(1)
#include <bits/stdc++.h>
using namespace std;
// using 1 queue
/*
class Queue {
queue<int> q;
public:
void push(int x) {
int s = q.size();
q.push(x);
for(int i =0; i<s; i++) {
q.push(q.front());
q.pop();
}
}
int pop() {
if(q.empty()) {
return -1;
}
int x = q.front();
q.pop();
return x;
}
int front() {
if(q.empty()) {
return -1;
}
return q.front();
}
};
*/
// using 2 queues
class Queue {
queue<int> q1, q2;
public:
void push(int x) {
q2.push(x);
while(!q1.empty()) {
q2.push(q1.front());
q1.pop();
}
queue<int> q = q1;
q1 = q2;
q2 = q;
}
int pop() {
if(q1.empty()) {
return -1;
}
int x = q1.front();
q1.pop();
return x;
}
int front() {
if(q1.empty()) {
return -1;
}
return q1.front();
}
};
int main() {
Queue q;
q.push(2);
q.push(9);
q.push(5);
cout << q.pop() <<endl;
cout<< q.front() << endl;
return 0;
}