算法第八天 —— 用栈实现队列 用队列实现栈

84 阅读2分钟

232. 用栈实现队列

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):实现 MyQueue 类:

  • void push(int x)` 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

  • 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

解题思路:

利用栈先进后出、队列先进先出的特性,使用双栈来实现;

注意:双栈分为入栈、出栈两个栈,只有当出栈的的元素全部出去,才可以讲入栈的加入到出栈栈

 public 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() {
         put();
         return stackOut.pop();
     }
 ​
     public int peek() {
         put();
         return stackOut.peek();
     }
 ​
     public boolean empty() {
         return stackOut.isEmpty() && stackIn.isEmpty();
     }
 ​
     private void put() {
         if (!stackOut.isEmpty()) return; //必须保证out没有了才开始讲in的加入,否则后续进入的会在上面
         while (!stackIn.isEmpty()) {
             stackOut.push(stackIn.pop());
         }
     }
 }
 ​

225 用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

解题思路:首先将元素添加到队列中,然后将辅助队列的元素,放到队列中,交互那队列和辅助队列

后面从辅助队列中取出数据

 public class MyStack {
 ​
     public Queue<Integer> inQueue;
     public Queue<Integer> outQueue;
 ​
     public MyStack() {
         inQueue = new LinkedList<>();
         outQueue = new LinkedList<>();
     }
 ​
     public void push(int x) {
 ​
         inQueue.offer(x);
         while (!outQueue.isEmpty()) { // 首先将元素添加到队列中,然后将辅助队列的元素,放到队列中,交互那队列和辅助队列
             inQueue.offer(outQueue.poll());
         }
         Queue<Integer> queueTemp;
         queueTemp = outQueue;
         outQueue = inQueue;
         inQueue = queueTemp;
 ​
     }
 ​
     public int pop() {
         return outQueue.poll();
     }
 ​
     public int top() {
         return outQueue.peek();
     }
 ​
     public boolean empty() {
         return outQueue.isEmpty();
     }
 }
 ​