forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueueusingstack.cpp
More file actions
96 lines (82 loc) · 2.02 KB
/
Copy pathqueueusingstack.cpp
File metadata and controls
96 lines (82 loc) · 2.02 KB
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
// Time Complexity :all operations T(n) = O(n) ==> push,peek,pop ; T(n)=O(1) ==> empty
// Space Complexity :S(n)=O(n)
// Did this code successfully run on Leetcode :yes
// Your code here along with comments explaining your approach
// used two stacks and shifted elements from one to other to achieve FIFO
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
stack<int> st1;
stack<int> st2;
/** Push element x to the back of queue. */
void push(int x)
{
if(st1.empty() && st2.empty())
{
st1.push(x);
return;
}
else if(st1.empty() && !st2.empty())
{
while(!st2.empty())
{
int temp=st2.top();
st1.push(temp);
st2.pop();
}
st1.push(x);
return;
}
else if(!st1.empty())
{
st1.push(x);
}
return;
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (!st2.empty())
{
int temp= st2.top();
st2.pop();
return temp;
}
else if(!st1.empty() && st2.empty())
{
while(!st1.empty())
{
int temp=st1.top();
st1.pop();
st2.push(temp);
}
int temp1=st2.top();
st2.pop();
return temp1;
}
return -9999;
}
/** Get the front element. */
int peek() {
if (!st2.empty())
{
return st2.top();
}
else if(!st1.empty() && st2.empty())
{
while(!st1.empty())
{
int temp=st1.top();
st1.pop();
st2.push(temp);
}
return st2.top();
}
return 0;
}
/** Returns whether the queue is empty. */
bool empty() {
return st1.empty() && st2.empty();
}
};