-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementQueueUsingStacks.java
More file actions
80 lines (69 loc) · 1.77 KB
/
ImplementQueueUsingStacks.java
File metadata and controls
80 lines (69 loc) · 1.77 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
69
70
71
72
73
74
75
76
77
78
79
80
package leetcode;
import java.util.Stack;
/**
* ImplementQueueUsingStacks
* https://leetcode-cn.com/problems/implement-queue-using-stacks/
* 232. 用栈实现队列
* https://leetcode-cn.com/problems/implement-queue-using-stacks/solution/shuang-zhan-shi-xian-dui-lie-by-oshdyr-fm7c/
*
* @since 2021-03-05
*/
public class ImplementQueueUsingStacks {
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(3);
queue.push(8);
System.out.println(queue.peek());
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.peek());
System.out.println(queue.empty());
System.out.println(queue.pop());
System.out.println(queue.empty());
}
}
class MyQueue {
Stack<Integer> main;
Stack<Integer> support;
/**
* Initialize your data structure here.
*/
public MyQueue() {
main = new Stack<>();
support = new Stack<>();
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
while (!support.isEmpty()) {
main.add(support.pop());
}
main.add(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
while (!main.isEmpty()) {
support.add(main.pop());
}
return support.pop();
}
/**
* Get the front element.
*/
public int peek() {
while (!main.isEmpty()) {
support.add(main.pop());
}
return support.peek();
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return main.isEmpty() && support.isEmpty();
}
}