forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyStack.java
More file actions
52 lines (44 loc) · 1 KB
/
MyStack.java
File metadata and controls
52 lines (44 loc) · 1 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
package normal;
import java.util.LinkedList;
import java.util.Queue;
/**
* @program JavaBooks
* @description: 225.用队列实现栈
* @author: mf
* @create: 2019/11/07 15:10
*/
/*
题目:https://leetcode-cn.com/problems/implement-stack-using-queues/
类型:队列
难度:easy
*/
public class MyStack {
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
System.out.println(myStack.pop());
}
private Queue<Integer> queue;
// private LinkedList<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.add(x);
int cnt = queue.size();
while (cnt-- > 1) {
queue.add(queue.poll());
}
// queue.addFirst(x);
}
public int pop() {
return queue.remove();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}