栈 stack
- 先进后出
- 可以用链表、数组实现栈的结构
java中容器:
- 类:
java.util.Stack<>
- 函数:
push()
:压入元素pop()
:弹出栈顶元素,并返回栈顶元素peek()
:返回栈顶元素size()
:返回长度empty()
:栈是否为空clear()
:清空
队列 queue
- 先进先出
- 可以用数组实现队列
java中容器:
- 接口:
java.util.Queue<>
- 实现:
java.util.LinkedList<>
:双链表java.util.PriorityQueue<>
:优先队列- 默认是小根堆,大根堆写法:
new PriorityQueue<>(Collections.reverseOrder())
- 默认是小根堆,大根堆写法:
- 函数:
add()
:在队尾添加元素remove()
:删除并返回队头isEmpty()
:是否为空size()
:返回长度peek()
:返回队头clear()
:清空
leetcode 232
题目链接
用栈实现队列
思路:
- 用2个
stack
实现 - 可以画图,思考过程
.pop()
和.peek()
时要把第一个栈中的所有元素全部移至第二个栈中
class MyQueue {
Stack<Integer> s1, s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x) {
s1.push(x);
}
public int pop() {
if (s2.empty()) {
while (!s1.empty())
s2.push(s1.pop());
}
int res = s2.pop(); //store the result
while (!s2.empty())
s1.push(s2.pop());
return res;
}
public int peek() {
if (s2.empty()) {
while (!s1.empty())
s2.push(s1.pop());
}
int res = s2.peek(); //store the result
while (!s2.empty()) //把s2中所有元素再移回s1,便于后续再次压入元素
s1.push(s2.pop());
return res;
}
public boolean empty() {
return s1.empty();
}
}
leetcode 225
题目链接
用队列实现栈
思路:
- like leetcode 232,还是画图
- 用2个队列去模拟栈的操作
note:
- java中队列容器定义是
Queue<x> q = new LinkedList<>()
- 队列的函数是
add()
&remove()
&isEmpty()
&peek()
- 栈的函数是
push()
&pop()
&empty()
&peek()
class MyStack {
Queue<Integer> q1, q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
q1.add(x);
}
public int pop() {
int res = 0;
if (q2.isEmpty()) {
while (q1.size() > 1)
q2.add(q1.remove());
}
res = q1.remove();
while (!q2.isEmpty())
q1.add(q2.remove());
return res;
}
public int top() {
int res = 0;
if (q2.isEmpty()) {
while (!q1.isEmpty()) {
res = q1.remove();
q2.add(res);
}
}
while (!q2.isEmpty())
q1.add(q2.remove());
return res;
}
public boolean empty() {
return q1.isEmpty();
}
}