Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 601
Expand file tree
/
Copy pathImplementStackUsingQueues.java
More file actions
Latest commit
60 lines (50 loc) · 1.28 KB
/
Copy pathImplementStackUsingQueues.java
File metadata and controls
60 lines (50 loc) · 1.28 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
packageproblems.easy;
importjava.util.LinkedList;
importjava.util.Queue;
/**
* Created by sherxon on 2016-12-29.
*/
publicclassImplementStackUsingQueues {
staticclassMyStack {
Queue<Integer> q;
Queue<Integer> temp;
/**
* Initialize your data structure here.
*/
publicMyStack() {
q = newLinkedList<>();
temp = newLinkedList<>();
}
/**
* Push element x onto stack.
*/
publicvoidpush(intx) {
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.
*/
publicintpop() {
returnq.poll();
}
/**
* Get the top element.
*/
publicinttop() {
returnq.peek();
}
/**
* Returns whether the stack is empty.
*/
publicbooleanempty() {
returnq.isEmpty();
}
}
}