目录
- 232. 用栈实现队列
- 剑指 Offer 09. 用两个栈实现队列
232. 用栈实现队列
232. 用栈实现队列
解法:
使用两个栈来实现,很好理解,
一个来反转元素的入队顺序,
另一个来存储元素的最终顺序
/**
* 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();
*/
class MyQueue {
private Stack<Integer> a;
private Stack<Integer> b;
//队列初始化
public MyQueue() {
a = new Stack<>();
b = new Stack<>();
}
//入队操作
public void push(int x) {
a.push(x);
}
//出队操作
public int pop() {
//如果b栈为空,则将a栈全部弹出并压入b栈中,然后b.pop()
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.pop();
}
//返回队列开头元素
public int peek() {
if(b.isEmpty()){
while(!a.isEmpty()){
b.push(a.pop());
}
}
return b.peek();
}
//判断是否为空
public boolean empty() {
return a.isEmpty()&&b.isEmpty();
}
}
剑指 Offer 09. 用两个栈实现队列
https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
class CQueue {
//这个就是完成队尾插入和队头删除的功能
private Stack<Integer> a;
private Stack<Integer> b;
//初始化
public CQueue() {
a=new Stack<>();
b=new Stack<>();
}
//队列尾部插入
public void appendTail(int value) {
a.push(value);
}
//头部删除
public int deleteHead() {
if(!b.isEmpty()){
return b.pop();
}
if(a.isEmpty()){
return -1;
}
// if(b.isEmpty()){
// while(!a.isEmpty()){
// b.push(a.pop());
// }
// }
while(!a.isEmpty()){
b.push(a.pop());
}
return b.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
注意点:
这道题需要考虑到a、b栈都为空了
思路:其实在弹栈的时候只需要考虑4种情况即可
- a = null 、b = null
- a = null 、 b != null
- a != null 、b = null
- a != null、b != null
Stack<Integer> A;
Stack<Integer> B;
public CQueue() {
A = new Stack<Integer>();
B = new Stack<Integer>();
}
public void appendTail(int val){
A.push(val);
}
public int deleteHead(){
// B不为空,将B的值弹出
if(!B.isEmpty()){
return B.pop();
}
// A为空,返回-1
// 注意:此处必须要放在下面,这是因为Stack操作会删除元素,此时A已经是空的了
if(A.isEmpty()){
return -1;
}
/*
A B
|-| |-|
|5| |1|
|4| |2|
|3| |3|
|2| |4|
|1| |5|
*/
// 运行到这说明,B为空,需要将A的值赋给B,形成了一次倒叙
while(!A.isEmpty()){
B.push(A.pop());
}
return B.pop();
}