forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyQueue.java
More file actions
68 lines (59 loc) · 1.34 KB
/
MyQueue.java
File metadata and controls
68 lines (59 loc) · 1.34 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package normal;
import java.util.Stack;
/**
* @program JavaBooks
* @description: 232.用栈实现队列
* @author: mf
* @create: 2019/11/07 14:55
*/
/*
题目:https://leetcode-cn.com/problems/implement-queue-using-stacks/
类型:栈
难度:easy
*/
/*
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
*/
public class MyQueue {
private Stack<Integer> in;
private Stack<Integer> out;
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.push(1);
myQueue.push(2);
System.out.println(myQueue.peek());
System.out.println(myQueue.pop());
System.out.println(myQueue.empty());
}
public MyQueue() {
in = new Stack<>();
out = new Stack<>();
}
public void push (int x) {
in.push(x);
}
public int pop () {
if (out.isEmpty()) {
while (! in.isEmpty()) {
out.push(in.pop());
}
}
return out.pop();
}
public int peek () {
if (out.isEmpty()) {
while (! in.empty()) {
out.push(in.pop());
}
}
return out.peek();
}
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}