forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue-using-stack.cpp
76 lines (65 loc) · 1.83 KB
/
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
// Time Complexity : push O(1) , pop - amortized O(1) might be O(n) in worst case. , peek amortized O(1) , might be O(n) in worst case, empty O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : YES
// Any problem you faced while coding this : NONE
// Your code here along with comments explaining your approach
class MyQueue {
stack<int>pushstack;
stack<int>popstack;
public:
MyQueue() {
}
void push(int x) {
pushstack.push( x );
}
int pop() {
if( popstack.size() ){
int elem = popstack.top();
popstack.pop();
return elem;
}
if( pushstack.size() ){
while( pushstack.size() ){
int elem = pushstack.top();
popstack.push( elem );
pushstack.pop();
}
int elem = popstack.top();
popstack.pop();
return elem;
} else {
// no elem present
return INT_MIN;
}
}
int peek() {
if( popstack.size() ){
return popstack.top();
}
if( pushstack.size() ){
while( pushstack.size() ){
int elem = pushstack.top();
popstack.push( elem );
pushstack.pop();
}
return popstack.top();
} else {
// no elem present
return INT_MIN;
}
}
bool empty() {
if( popstack.size() == 0 && pushstack.size() == 0 ){
return true;
}
return false;
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/