1. 用栈实现队列

使用栈实现队列的下列操作:

push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。

https://leetcode-cn.com/problems/implement-queue-using-stacks

栈的顺序为后进先出,而队列的顺序为先进先出。使用两个栈实现队列,一个元素需要经过两个栈才能出队列,在经过第一个栈时元素顺序被反转,经过第二个栈时再次被反转,此时就是先进先出顺序。

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
package com.lq.leetcode.stack;

import java.util.Stack;

public class MyQueue {

private Stack<Integer> in = new Stack<>();
private Stack<Integer> out = new Stack<>();

/** Initialize your data structure here. */
public MyQueue() {

}

/** Push element x to the back of queue. */
public void push(int x) {
in.push(x);
}

/** Removes the element from in front of queue and returns that element. */
public int pop() {
in2out();
return out.pop();
}

public void in2out(){
if (out.isEmpty()){
while (!in.isEmpty()){
out.push(in.pop());
}
}
}

/** Get the front element. */
public int peek() {
in2out();
return out.peek();
}

/** Returns whether the queue is empty. */
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}

2. 用队列实现栈

225

在将一个元素 x 插入队列时,为了维护原来的后进先出顺序,需要让 x 插入队列首部。而队列的默认插入顺序是队列尾部,因此在将 x 插入队列尾部之后,需要让除了 x 之外的所有元素出队列,再入队列。

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
public class MyStack {
private Queue<Integer> queue;

/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}

/** Push element x onto stack. */
//每次将插入的数据重新插入
public void push(int x) {
queue.add(x);
int size = queue.size();
while (size-->1){
queue.add(queue.poll());
}
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue.poll();
}

/** Get the top element. */
public int top() {
return queue.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}

}

3. 最小值栈

155

fig1

按照上面的思路,我们只需要设计一个数据结构,使得每个元素 a 与其相应的最小值 m 时刻保持一一对应。因此我们可以使用一个辅助栈,与元素栈同步插入与删除,用于存储与每个元素对应的最小值。

当一个元素要入栈时,我们取当前辅助栈的栈顶存储的最小值,与当前元素比较得出最小值,将这个最小值插入辅助栈中;

当一个元素要出栈时,我们把辅助栈的栈顶元素也一并弹出;

在任意一个时刻,栈内元素的最小值就存储在辅助栈的栈顶元素中。

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
public class MinStack {

private Stack<Integer> dataStack;
private Stack<Integer> minStack;
private int min;

public MinStack() {
dataStack = new Stack<>();
minStack = new Stack<>();
min = Integer.MAX_VALUE;
}

public void push(int x) {
dataStack.add(x);
min = Math.min(min, x);
minStack.add(min);
}

public void pop() {
dataStack.pop();
minStack.pop();
min = minStack.isEmpty() ? Integer.MAX_VALUE : minStack.peek();
}

public int top() {
return dataStack.peek();
}

public int getMin() {
return minStack.peek();
}
}