232.用栈实现队列
题目链接:232. 用栈实现队列
文档讲解:代码随想录
状态:写出来 ,但差强人意
思路: 定义两个容器,可以是Stack,也可以是Deque,stackIn相当于临时容器,用来存放元素,stackOut相当于最终容器,当需要查看或返回元素时,会把stackIn中的元素往stackOut中汇总一次。
题解:
public class MyQueue_232 {//stackIn相当于临时容器,用来存放元素//stackOut相当于最终容器,当需要查看或返回元素时,会把stackIn中的元素往stackOut中汇总一次Deque<Integer> stackIn;Deque<Integer> stackOut;public MyQueue_232() {stackIn = new ArrayDeque<>();stackOut = new ArrayDeque<>();}public void push(int x) {stackIn.push(x);}//当stackOut为空时,stackIn中元素存入stackOut中public int pop() {if (stackOut.isEmpty()) {inToOut();}return stackOut.pop();}public int peek() {if (stackOut.isEmpty()) {inToOut();}return stackOut.peek();}public boolean empty() {return stackIn.isEmpty() && stackOut.isEmpty();}void inToOut() {while (!stackIn.isEmpty()) {stackOut.push(stackIn.pop());}}@Overridepublic String toString() {return "MyQueue_232{" +"stackIn=" + stackIn +", stackOut=" + stackOut +'}';}
225.用队列实现栈
题目链接:225.用队列实现栈
文档讲解:代码随想录
状态:没啥好说的
题解:
class MyStack {Deque<Integer> deque1 = new LinkedList<>();Deque<Integer> deque2 = new LinkedList<>();public void push(int x) {deque1.push(x);deque2.push(x);}public int pop() {deque1.pollLast();return deque2.poll();}public int top() {return deque2.peek();}public boolean empty() {return deque2.isEmpty();}}