-
Notifications
You must be signed in to change notification settings - Fork 1
/
Q9_UseStackRealizeQueue.java
96 lines (75 loc) · 2.14 KB
/
Q9_UseStackRealizeQueue.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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package jianzhi_offer;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* LeetCode 232
*
* @author weiyuwang
* @since 2019/1/23 14:18
*/
public class Q9_UseStackRealizeQueue {
/**
* 用两个栈实现队列
*/
class MyQueue {
Deque<Integer> stack = new ArrayDeque<>();
Deque<Integer> sup = new ArrayDeque<>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
while(!stack.isEmpty()){
sup.addFirst(stack.removeFirst());
}
sup.addFirst(x);
while(!sup.isEmpty()){
stack.addFirst(sup.removeFirst());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return stack.removeFirst();
}
/** Get the front element. */
public int peek() {
return stack.getFirst();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack.isEmpty();
}
}
/**
* 用队列实现栈
*/
class MyStack {
Deque<Integer> queue = new ArrayDeque<>();
Deque<Integer> queue1 = new ArrayDeque<>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
while(!queue.isEmpty()){
queue1.addLast(queue.removeFirst());
}
queue.addLast(x);
while(!queue1.isEmpty()){
queue.addLast(queue1.removeFirst());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.removeFirst();
}
/** Get the top element. */
public int top() {
return queue.getFirst();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}
}