本文主要是介绍代码随想录训练营第三十期|第十天|栈与队列part01|理论基础● 232.用栈实现队列● 225. 用队列实现栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
232. 用栈实现队列 - 力扣(LeetCode)
class MyQueue {Stack<Integer> in;Stack<Integer> out;public MyQueue() {in = new Stack<>();out = new Stack<>();}public void push(int x) {in.push(x);}public int pop() {move();return out.pop();}public int peek() {move();return out.peek();}public boolean empty() {return in.isEmpty() && out.isEmpty();}private void move() {if (out.isEmpty()) {while (!in.isEmpty()) {out.push(in.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. 用队列实现栈 - 力扣(LeetCode)
class MyStack {Queue<Integer> queue1;Queue<Integer> queue2;public MyStack() {queue1 = new LinkedList<>();queue2 = new LinkedList<>();}public void push(int x) {queue2.offer(x);while (!queue1.isEmpty()) {queue2.offer(queue1.poll());}Queue<Integer> tmp;tmp = queue1;queue1 = queue2;queue2 = tmp;}public int pop() {return queue1.poll();}public int top() {return queue1.peek();}public boolean empty() {return queue1.isEmpty();}
}/*** Your MyStack object will be instantiated and called as such:* MyStack obj = new MyStack();* obj.push(x);* int param_2 = obj.pop();* int param_3 = obj.top();* boolean param_4 = obj.empty();*/
这篇关于代码随想录训练营第三十期|第十天|栈与队列part01|理论基础● 232.用栈实现队列● 225. 用队列实现栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!