232.用栈实现队列
232. 用栈实现队列https://leetcode.cn/problems/implement-queue-using-stacks/思路:两个栈,一个栈只用于push进入,另一个栈只用于out输出,只能明确,每次pop之前把所有inStack都移动到out中,很好实现
import java.util.Stack;
//leetcode submit region begin(Prohibit modification and deletion)
class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
inStack=new Stack<Integer>();
outStack=new Stack<>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if(outStack.isEmpty()){
in2Out();
}
return outStack.pop();
}
public int peek() {
if(outStack.isEmpty()){
in2Out();
}
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
public void in2Out(){
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
}
225. 用队列实现栈
225. 用队列实现栈https://leetcode.cn/problems/implement-stack-using-queues/
思路:思路没有之前那么清晰,但是整体思路没差多少,因为push的时候怎么接收都行,主要是pop的时候需要先进后出,其实这里只用一个队列也可以实现栈,另一个队列完全是辅助中间存储使用,每次push的时候倒腾一下顺序,保证queue始终倒序存储的,这样pop和peek就不需要每次都处理了 直接poll()和peek()就行了。
import java.util.LinkedList;
import java.util.Queue;
//leetcode submit region begin(Prohibit modification and deletion)
class MyStack {
Queue<Integer> queue;
Queue<Integer> tempQueue;
public MyStack() {
queue=new LinkedList<Integer>();
tempQueue=new LinkedList<Integer>();
}
public void push(int x) {
while(queue.size()>0){
tempQueue.offer(queue.poll());
}
queue.add(x);
while(tempQueue.size()>0){
queue.offer(tempQueue.poll());
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return tempQueue.isEmpty() && queue.isEmpty();
}
}
进阶版:用一个队列实现栈,其实代码没差啥:
import java.util.LinkedList;
import java.util.Queue;
//leetcode submit region begin(Prohibit modification and deletion)
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue=new LinkedList<Integer>();
}
public void push(int x) {
Queue<Integer> tempQueue=new LinkedList<Integer>();
while(queue.size()>0){
tempQueue.offer(queue.poll());
}
queue.add(x);
while(tempQueue.size()>0){
queue.offer(tempQueue.poll());
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}