forked from yuhailei1992/Java7SourceCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementStackUsingQueue.java
More file actions
74 lines (65 loc) · 1.69 KB
/
ImplementStackUsingQueue.java
File metadata and controls
74 lines (65 loc) · 1.69 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Solution 1: use two queues;
* Solution 2: use only one queue;
* Solution 3:
*/
class MyStack {
private Queue<Integer> qFront = new LinkedList<Integer>();
private Queue<Integer> qBack = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
qBack.add(x);
}
// Removes the element on top of the stack.
public void pop() {
if (qBack.isEmpty()) {
while (!qFront.isEmpty()) {
qBack.add(qFront.poll());
}
}
while (qBack.size() != 1) {
qFront.add(qBack.poll());
}
// get rid of the last one (stack top).
qBack.poll();
}
// Get the top element.
public int top() {
if (qBack.isEmpty()) {
while (!qFront.isEmpty()) {
qBack.add(qFront.poll());
}
}
while (qBack.size() != 1) {
qFront.add(qBack.poll());
}
return qBack.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return qBack.isEmpty() && qFront.isEmpty();
}
}
// Solution 2:
class MyStack {
private Queue<Integer> queue = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
queue.add(x);
for (int i = 0; i < queue.size() - 1; i++) {
queue.add(queue.poll());
}
}
// Removes the element on top of the stack.
public void pop() {
queue.poll();
}
// Get the top element.
public int top() {
return queue.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}