forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyStack.java
82 lines (68 loc) · 1.69 KB
/
MyStack.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.LinkedList;
import java.util.Queue;
/**
* https://leetcode.com/articles/implement-stack-using-queues/
*/
public class MyStack {
private Queue<Integer> mQueue, mQueueTmp;
public MyStack() {
mQueue = new LinkedList<Integer>();
mQueueTmp = new LinkedList<Integer>();
}
// Push element x onto stack.
public void push(int x) {
mQueue.add(x);
}
// Removes the element on top of the stack.
public void pop() {
while (!mQueue.isEmpty()) {
int n = mQueue.poll();
if (!mQueue.isEmpty()) {
mQueueTmp.add(n);
}
}
swap();
}
private void swap() {
Queue<Integer> queue = mQueue;
mQueue = mQueueTmp;
mQueueTmp = queue;
}
// Get the top element.
public int top() {
int top = 0;
while (!mQueue.isEmpty()) {
top = mQueue.poll();
mQueueTmp.add(top);
}
swap();
return top;
}
// Return whether the stack is empty.
public boolean empty() {
return mQueue.isEmpty();
}
/** 这种做法只用一个Queue
private LinkedList<Integer> q1 = new LinkedList<>();
// Push element x onto stack.
public void push(int x) {
q1.add(x);
int sz = q1.size();
while (sz > 1) {
q1.add(q1.remove());
sz--;
}
}
// Removes the element on top of the stack.
public void pop() {
q1.remove();
}
// Get the top element.
public int top() {
return q1.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return q1.isEmpty();
}*/
}