莱芜市网站建设公司,杭州有奖举报,深圳罗湖的网站建设,微网站营销是什么文章目录 力扣225. 用队列实现栈示例思路及其实现两个队列模拟栈一个队列模拟栈 力扣225. 用队列实现栈 示例 思路及其实现
两个队列模拟栈
队列是先进先出的规则#xff0c;把一个队列中的数据导入另一个队列中#xff0c;数据的顺序并没有变#xff0c;并没有变成先进后… 文章目录 力扣225. 用队列实现栈示例思路及其实现两个队列模拟栈一个队列模拟栈 力扣225. 用队列实现栈 示例 思路及其实现
两个队列模拟栈
队列是先进先出的规则把一个队列中的数据导入另一个队列中数据的顺序并没有变并没有变成先进后出的顺序。
所以用栈实现队列 和用队列实现栈的思路还是不一样的这取决于这两个数据结构的性质。
但是依然还是要用两个队列来模拟栈只不过没有输入和输出的关系而是另一个队列完全用来备份的
用两个队列que1和que2实现队列的功能que2其实完全就是一个备份的作用把que1最后面的元素以外的元素都备份到que2然后弹出最后面的元素再把其他元素从que2导回que1。
代码如下
class MyStack {QueueInteger queue1; // 和栈中保持一样元素的队列QueueInteger queue2; // 辅助队列/** Initialize your data structure here. */public MyStack() {queue1 new LinkedList();queue2 new LinkedList();}/** Push element x onto stack. */public void push(int x) {queue2.offer(x); // 先放在辅助队列中while (!queue1.isEmpty()){queue2.offer(queue1.poll());}QueueInteger queueTemp;queueTemp queue1;queue1 queue2;queue2 queueTemp; // 最后交换queue1和queue2将元素都放到queue1中}/** Removes the element on top of the stack and returns that element. */public int pop() {return queue1.poll(); // 因为queue1中的元素和栈中的保持一致所以这个和下面两个的操作只看queue1即可}/** Get the top element. */public int top() {return queue1.peek();}/** Returns whether the stack is empty. */public boolean empty() {return queue1.isEmpty();}
}
一个队列模拟栈
一个队列在模拟栈弹出元素的时候只要将队列头部的元素除了最后一个元素外 重新添加到队列尾部此时再去弹出元素就是栈的顺序了。
class MyStack {QueueInteger queue;public MyStack() {queue new LinkedList();}//每 offer 一个数A进来都重新排列把这个数A放到队列的队首public void push(int x) {queue.offer(x);int size queue.size();//移动除了 A 的其它数while (size-- 1)queue.offer(queue.poll());}public int pop() {return queue.poll();}public int top() {return queue.peek();}public boolean empty() {return queue.isEmpty();}
}