链接
牛客:用两个栈实现队列
LeetCode:剑指 Offer 09. 用两个栈实现队列
思路
这里主要考虑栈和队列的异同,栈是现先进后出,队列是先进先出。
设置两个栈,其中第一个压入值=,和队列是一样的功能。
第二个栈压入第一个栈弹出的值,这时第二个栈先弹出的就是第一个栈先进入的,和队列的先进先出保持一致。两个栈的操作就变成了一个队列的操作。
涉及到栈和队列或者说链表这类数据结构的问题可以考虑下画图,会清晰很多。
代码
牛客:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (stack2.size() == 0) {
while (stack1.size() > 0) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
LeetCode:
class CQueue {
private Stack<Integer> stack1 = new Stack<>();
private Stack<Integer> stack2 = new Stack<>();
public CQueue() {
}
public void appendTail(int value) {
stack1.push(value);
}
public int deleteHead() {
if (stack2.size() == 0) {
while (stack1.size() > 0) {
stack2.push(stack1.pop());
}
}
if (stack2.isEmpty()){
return -1;
}
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();
*/
类似题
参考:232. 用栈实现队列
class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
/**
* Initialize your data structure here.
*/
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
stack1.push(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/**
* Get the front element.
*/
public int peek() {
int res = pop(); // 直接使用已有的pop函数
stack2.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return stack1.isEmpty() && stack2.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();
*/