-
-
Notifications
You must be signed in to change notification settings - Fork 611
/
ImplementStackUsingQueues.java
60 lines (50 loc) · 1.28 KB
/
ImplementStackUsingQueues.java
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
package problems.easy;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by sherxon on 2016-12-29.
*/
public class ImplementStackUsingQueues {
static class MyStack {
Queue<Integer> q;
Queue<Integer> temp;
/**
* Initialize your data structure here.
*/
public MyStack() {
q = new LinkedList<>();
temp = new LinkedList<>();
}
/**
* Push element x onto stack.
*/
public void push(int x) {
if (q.isEmpty()) q.add(x);
else {
while (!q.isEmpty()) // copy all to helper
temp.add(q.poll());
q.add(x); // add element
while (!temp.isEmpty()) // copy back all to helper
q.add(temp.poll());
}
}
/**
* Removes the element on top of the stack and returns that element.
*/
public int pop() {
return q.poll();
}
/**
* Get the top element.
*/
public int top() {
return q.peek();
}
/**
* Returns whether the stack is empty.
*/
public boolean empty() {
return q.isEmpty();
}
}
}