前言:
刷烂力扣,刷进大厂!!!
用两个栈实现队列
题目描述:
解题思路:
代码实现:
class CQueue {
// 先初始化两个栈来设计队列
public Stack<Integer> stackA;
public Stack<Integer> stackB;
public CQueue() {
// 实例化栈
stackA = new Stack<>();
stackB = new Stack<>();
}
// 队列尾部插入
public void appendTail(int value) {
// 先将栈B的元素弹入栈A
if(!stackB.isEmpty()) {
stackA.push(stackB.pop());
}
// 栈A最后加入Value
stackA.push(value);
}
// 头部删除
public int deleteHead() {
// 如果不为空,先将栈A的元素弹入栈B,此时栈B的尾部为队列的头部
while (!stackA.isEmpty()) {
stackB.push(stackA.pop());
}
// 先判断栈B是不是空
if(stackB.isEmpty()) {
return -1;
}
return stackB.pop();
}
}
方法二:
这个方法是借用力扣一个大佬的思路,我感觉很强!
如果你使用Stack的方式来做这道题,会造成速度较慢
;原因
是Stack继承了Vector接口,而Vector底层是一个Object[]数组,那么就要考虑空间扩容和移位的问题了。 可以使用LinkedList来做Stack的容器,因为LinkedList实现了Deque接口,所以Stack能做的事LinkedList都能做
,其本身结构是个双向链表,扩容消耗少。
代码实现:
class CQueue {
LinkedList<Integer> stack1;
LinkedList<Integer> stack2;
public CQueue() {
stack1 = new LinkedList<>();
stack2 = new LinkedList<>();
}
public void appendTail(int value) {
stack1.add(value);
}
public int deleteHead() {
if (stack2.isEmpty()) {
if (stack1.isEmpty()) return -1;
while (!stack1.isEmpty()) {
stack2.add(stack1.pop());
}
return stack2.pop();
} else return stack2.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
包含min函数的栈
解题思路:
一点:借用辅助栈B,B中存储最小元素
代码实现:
class MinStack {
Stack<Integer> A,B;
/** initialize your data structure here. */
public MinStack() {
A = new Stack<>();
B = new Stack<>();
}
public void push(int x) {
A.add(x);
if(B.empty() || x<= B.peek()) {
B.add(x);
}
}
public void pop() {
if(A.pop().equals(B.peek())) {
B.pop();
}
}
public int top() {
return A.peek();
}
public int min() {
return B.peek();
}
}