-
Notifications
You must be signed in to change notification settings - Fork 0
/
232. 用栈实现队列.java
78 lines (67 loc) · 1.77 KB
/
232. 用栈实现队列.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
/**
* 两种不同的实现思想
*/
class MyQueue {
Deque<Integer> stack;
Deque<Integer> util;
/** Initialize your data structure here. */
public MyQueue() {
stack = new LinkedList<>();
util = new LinkedList<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
while(stack.size() > 0){
util.offerLast(stack.pollLast());
}
util.offerLast(x);
while(util.size() > 0){
stack.offerLast(util.pollLast());
}
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
return stack.pollLast();
}
/** Get the front element. */
public int peek() {
return stack.peekLast();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack.isEmpty();
}
}
class MyQueue {
Deque<Integer> stack;
Deque<Integer> util;
/** Initialize your data structure here. */
public MyQueue() {
stack = new LinkedList<>();
util = new LinkedList<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
peek();
int res = stack.pop();
while(util.size() > 0){
stack.push(util.pop());
}
return res;
}
/** Get the front element. */
public int peek() {
while(stack.size() > 1){
util.push(stack.pop());
}
return stack.peekLast();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stack.isEmpty();
}
}