-
Notifications
You must be signed in to change notification settings - Fork 62
/
StackUseQueue.java
42 lines (34 loc) · 915 Bytes
/
StackUseQueue.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
package datastructure.queue.leetcode;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author roseduan
* 使用队列实现栈
*/
public class StackUseQueue {
private Queue<Integer> queue;
/** Initialize your data structure here. */
public StackUseQueue() {
this.queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
int n = queue.size();
queue.offer(x);
for (int i = 0; i < n; 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();
}
}