-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMyStack.java
42 lines (35 loc) · 876 Bytes
/
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
package leetcode.stackAndQueue.problem225;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created with IntelliJ IDEA
*
* @Author yuanhaoyue swithaoy@gmail.com
* @Description 225. 队列实现栈
* @Date 2018-12-07
* @Time 2:07
*/
class MyStack {
private Queue<Integer> q = new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
}
public void push(int x) {
q.add(x);
for(int i = 1; i < q.size(); i ++) { //rotate the queue to make the tail be the head
q.add(q.poll());
}
}
// Removes the element on top of the stack.
public int pop() {
return q.poll();
}
// Get the top element.
public int top() {
return q.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return q.isEmpty();
}
}