-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementStackUsingQueues.java
More file actions
56 lines (46 loc) · 1002 Bytes
/
Copy pathImplementStackUsingQueues.java
File metadata and controls
56 lines (46 loc) · 1002 Bytes
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
/**
* https://leetcode.com/problems/implement-stack-using-queues/
*/
package com.stack;
import java.util.ArrayDeque;
import java.util.Queue;
/**
* The idea here is put newly inserted element at the front of queue,
* which causes O(n) time for push() operation.
* @author Satish
*
*/
public class ImplementStackUsingQueues {
/**
* Push: O(n)
* Pop: O(1)
* Top: O(1)
*/
class MyStack {
Queue<Integer> q;
public MyStack() {
q = new ArrayDeque<>();
}
public void push(int x) {
q.offer(x);
// put this element at the front of queue
for (int i = 0; i < q.size() - 1; i++) {
q.offer(q.poll());
}
}
public int pop() {
return q.poll();
}
public int top() {
return q.peek();
}
public boolean empty() {
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such: MyStack obj =
* new MyStack(); obj.push(x); int param_2 = obj.pop(); int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
}