训练营Day10
今天开始学习栈和队列。
在Java中有一个类Stack
,它就是栈的实现类。但是我们打开文档的时候发现,文档却推荐使用Deque
实现栈操作。
经过上网查询,发现不推荐使用Stack的原因有两个:
- 继承Vector,可以随意对动态数组进行增删,违反栈的这种数据结构的封装
- Vector是线程安全的,每次操作都需要上锁,影响性能。
基于这两种原因,我们可以使用Deque
实现栈的操作。
# 232.用栈实现队列 (opens new window)
队列的标准操作
push 将元素x推到队列的末尾
pop 弹出栈
peek 返回队列开头的元素
boolean empty() 判断是否为空
class MyQueue {
Deque<Integer> stackIn; //入栈
Deque<Integer> stackOut; //出栈
public MyQueue() {
this.stackIn = new ArrayDeque<>();
this.stackOut = new ArrayDeque<>();
}
/**
* @param x 放到消息队列默认
*/
public void push(int x) {
stackIn.push(x);
}
/**
* @return 返回并移除队列前面的元素
*/
public int pop() {
//1.判断出栈是否为空
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
return stackOut.pop();
}
/**
* @return 返回队列前端 但不移除
*/
public int peek() {
//1.判断出栈是否为空
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
return stackOut.peek();
}
public boolean empty() {
return stackOut.isEmpty() && stackIn.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
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
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
# 225.用队列实现栈 (opens new window)
可以用栈实现队列,同样的也可以使用队列实现栈。
下面是一个就够了
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<Integer>();
}
/**
* @param x 往栈添加一个
*/
public void push(int x) {
int n = queue.size();
queue.add(x);
while (n>0){
Integer poll = queue.poll();
queue.add(poll);
n--;
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.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
29
30
31
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
上次更新: 2023/07/05, 01:23:13