● 232.用栈实现队列
dump:转储
在pop的时候,输出栈如果为空,就把进栈数据全部导入进来,这样就不会影响出栈的顺序
class MyQueue { Stack<Integer> stackIn; Stack<Integer> stackOut; public MyQueue() { stackIn = new Stack<>(); stackOut = new Stack<>(); } public void push(int x) { stackIn.push(x); } public int pop() { dumpStackIn(); return stackOut.pop(); } public int peek() { dumpStackIn(); return stackOut.peek();//peek 对应 peek } public boolean empty() { return stackOut.isEmpty()&&stackIn.empty(); } public void dumpStackIn(){ if(!stackOut.isEmpty()) return; //如果出栈没有元素,才去push(stackIn.pop()); while(!stackIn.empty()){ stackOut.push(stackIn.pop()); } } } /** * 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(); */
● 225. 用队列实现栈
class MyStack { Queue<Integer> queue; public MyStack() { queue = new LinkedList<>(); } public void push(int x) { queue.add(x); } public int pop() { rePosition(); return queue.poll(); } public int top() { rePosition(); int result = queue.poll(); queue.add(result); return result; } public boolean empty() { return queue.isEmpty(); } public void rePosition(){ int size = queue.size(); size--;//因为我们后面的 while(size-->0) queue.add(queue.poll()); } } 今天是我感觉最轻松的一天,终于可以做其他的事情了