队列与栈
# 232. 用栈实现队列 (opens new window)
class MyQueue {
private Stack<Integer> s1,s2;
public MyQueue() {
this.s1 = new Stack<>();
this.s2 = new Stack<>();
}
public void push(int x) {
s1.push(x);
}
public int pop() {
peek();
return s2.pop();
}
public int peek() {
if(s2.isEmpty()){
while(!s1.isEmpty())
s2.push(s1.pop());
}
return s2.peek();
}
public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}
}
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
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
# 622. 设计循环队列 (opens new window)
方法一:队列
class MyCircularQueue {
ListNode head;
ListNode tail;
int capacity; // 上限
int size;// 当前容量
public MyCircularQueue(int k) {
capacity = k;
size = 0;
}
public boolean enQueue(int value) {
if(isFull())
return false;
ListNode node = new ListNode(value);
if(head==null)
head = tail = node;
else{
tail.next = node;
tail = node;
}
size++;
return true;
}
public boolean deQueue() {
if(isEmpty())
return false;
ListNode node = head;
head = head.next;
size--;
return true;
}
public int Front() {
if(isEmpty())
return -1;
return head.val;
}
public int Rear() {
if(isEmpty())
return -1;
return tail.val;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
}
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
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
方法二:数组