网站地图样本,wordpress文章接口,大型网站设计公司,wordpress 手机版域名理论基础及Java实现参考文章#xff1a;栈和队列 一、LeetCode 232 用栈实现队列
题目链接#xff1a;232.用栈实现队列https://leetcode.cn/problems/implement-queue-using-stacks/ 思路#xff1a;使用两个栈stack1、stack2实现队列#xff1b;stack1用来存储入队元素栈和队列 一、LeetCode 232 用栈实现队列
题目链接232.用栈实现队列https://leetcode.cn/problems/implement-queue-using-stacks/ 思路使用两个栈stack1、stack2实现队列stack1用来存储入队元素stack2用于颠倒出栈顺序从而借助栈的后进先出实现队列的先进先出详见代码~ class MyQueue {StackInteger stack1,stack2;public MyQueue() {stack1 new Stack();stack2 new Stack();}public void push(int x) {//入队列时清空stack2全部加入stack1while(!stack2.empty()){stack1.push(stack2.pop());}//将新元素加入stack1stack1.push(x);}public int pop() {//出栈时把stack1中全部元素取出放到stack2中while(!stack1.empty()){stack2.push(stack1.pop());}//此时stack2栈顶元素为之前stack1栈底元素return stack2.pop();}public int peek() {while(!stack1.empty()){stack2.push(stack1.pop());}return stack2.peek();}public boolean empty() {return stack1.empty() stack2.empty();}
}/*** 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();*/
二、LeetCode 225 用队列实现栈
题目链接225.用队列实现栈https://leetcode.cn/problems/implement-stack-using-queues/ 思路创建队列q1、q2其中q1用来存储元素q2辅助暂存入栈时先把q2中的元素清空并全部入q1队出栈时也先把q2中的元素清空再把q1中元素依次入q2队留下最后一个元素(q1队尾元素)即为栈顶元素详见代码~ class MyStack {QueueInteger q1;QueueInteger q2;public MyStack() {//队列q1用来存储、q2用来暂存和备份q1 new LinkedList();q2 new LinkedList();}public void push(int x) {//先把q2中暂存的元素入队再把新元素入队确保整体顺序都为FIFOwhile(!q2.isEmpty()){q1.offer(q2.poll());}q1.offer(x);}public int pop() {//先把q2中的元素放回q1统一从q1中pop()while(!q2.isEmpty()){q1.offer(q2.poll());}//q1剩余最后一个元素即为队尾(栈头)元素while(q1.size() 1){q2.offer(q1.poll());}return q1.poll();}public int top() {while(!q2.isEmpty()){q1.offer(q2.poll());}while(q1.size() 1){q2.offer(q1.poll());}int ans q1.peek();//把q1中剩余的一个元素入q2队方便统一操作q2.offer(q1.poll());return ans;}public boolean empty() {//q1、q2均空时说明栈空return q1.isEmpty() q2.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();*/
三、今日小结 基础不牢地动山摇- 今天回顾了栈和队列的实现以及常用方法我对于栈与队列的相互实现的理解是要“构成闭环”OVO 这样才能确保不缺不漏、逻辑严谨。感觉我的代码还有很大的优化空间各位同志有改进建议的话随时欢迎批评指正~