-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path085_Queue Using Stack.cpp
133 lines (103 loc) · 2.55 KB
/
085_Queue Using Stack.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// Time Complexity -> O(n) push O(1) pop, peek
// Space Complexity -> O(2N) ~ O(N)
// costly enQueue
class Queue {
// Define the data members(if any) here.
stack<int> st1, st2;
public:
Queue() {
// Initialize your data structure here.
}
void enQueue(int val) {
// Implement the enqueue() function.
while(!st1.empty())
{
st2.push(st1.top());
st1.pop();
}
st1.push(val);
while(!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
}
int deQueue() {
// Implement the dequeue() function.
if(!st1.empty())
{
int ans = st1.top();
st1.pop();
return ans;
}
return -1;
}
int peek() {
// Implement the peek() function here.
if(!st1.empty())
{
return st1.top();
}
return -1;
}
bool isEmpty() {
// Implement the isEmpty() function here.
return st1.empty();
}
};
// Time Complexity -> O(1) push , worst O(n) or O(1) amortised pop, peek
// Space Complexity -> O(2N) ~ O(N)
// costly deQueue & peek O(n) but not in all instances and that's why we say it is O(1) amortised complexity
class Queue {
// Define the data members(if any) here.
stack<int> input, output;
public:
Queue() {
// Initialize your data structure here.
}
void enQueue(int val) {
// Implement the enqueue() function.
input.push(val);
}
int deQueue() {
// Implement the dequeue() function.
if(!output.empty())
{
int ans = output.top();
output.pop();
return ans;
}
else{
while(!input.empty())
{
output.push(input.top());
input.pop();
}
if(output.empty())
return -1;
else
return deQueue();
}
}
int peek() {
// Implement the peek() function here.
if(!output.empty())
{
return output.top();
}
else{
while(!input.empty())
{
output.push(input.top());
input.pop();
}
if(output.empty())
return -1;
return peek();
}
}
bool isEmpty() {
// Implement the isEmpty() function here.
return input.empty() && output.empty();
}
};