-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack232.java
More file actions
57 lines (46 loc) · 1.47 KB
/
Stack232.java
File metadata and controls
57 lines (46 loc) · 1.47 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
package stack;
import java.util.Stack;
public class Stack232 {
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
System.out.println(queue.peek()); // 返回 1
System.out.println(queue.pop()); // 返回 1
System.out.println(queue.empty()); // 返回 false
}
static class MyQueue {
private Stack<Integer> stackIn, stackOut;
/** Initialize your data structure here. */
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stackIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
return stackOut.pop();
}
/** Get the front element. */
public int peek() {
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
return stackOut.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
}
}