-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathImplementQueueusingStacks.java
More file actions
55 lines (46 loc) · 1.49 KB
/
ImplementQueueusingStacks.java
File metadata and controls
55 lines (46 loc) · 1.49 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
// Time Complexity : Amortized O(1) average case, worst case - O(n) for pop & peek
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no
// Your code here along with comments explaining your approach
/*
Maintain 2 stacks one for push operation and other for pop, peek operations. Whenever pop/peek happens,
push all the elements from inStack to outStack if outStack is empty, this way, we can have queue property
satisfied whenever peek or pop are called. As per question, all calls to pop and peek are valid, so
we need not check explicitly, if not, we need to validate inStack is not empty in those methods and return
-1 if so.
*/
class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack = new Stack<>();
outStack = new Stack<>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
peek();
return outStack.pop();
}
public int peek() {
if(outStack.isEmpty()) {
while(!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
}
/**
* 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();
* boolean param_4 = obj.empty();
*/