-
Notifications
You must be signed in to change notification settings - Fork 0
/
225. 用队列实现栈.java
74 lines (65 loc) · 1.66 KB
/
225. 用队列实现栈.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
/**
* 单队列实现方式
*/
class MyStack {
Queue<Integer> queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.offer(x);
for(int i = 0; i < queue.size() - 1; i++){
queue.offer(queue.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}
/** Get the top element. */
public int top() {
return queue.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
/**
* 双队列实现方式
*/
class MyStack {
Queue<Integer> myStack1;
Queue<Integer> myStack2;
/** Initialize your data structure here. */
public MyStack() {
myStack1 = new LinkedList<>();
myStack2 = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
myStack1.offer(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
top();
int res = myStack1.poll();
Queue<Integer> temp = myStack1;
myStack1 = myStack2;
myStack2 = temp;
return res;
}
/** Get the top element. */
public int top() {
while(myStack1.size() > 1){
myStack2.offer(myStack1.poll());
}
return myStack1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return myStack1.isEmpty();
}
}