首页 > 编程语言 >代码随想录算法Day10 | 理论基础 232.用栈实现队列 225. 用队列实现栈

代码随想录算法Day10 | 理论基础 232.用栈实现队列 225. 用队列实现栈

时间:2023-02-12 14:35:16浏览次数:62  
标签:队列 随想录 pop que1 int 用栈 push public

理论基础

栈是先进后出,队列是先进先出。如图所示。

232.用栈实现队列

题目链接:232. 用栈实现队列 - 力扣(LeetCode)

题目

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 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(双端队列)来模拟一个栈,只要是标准的栈操作即可。
 

示例 1:

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

思路

使用栈来模式队列的行为,如果仅仅用一个栈,是一定不行的,所以需要两个栈一个输入栈,一个输出栈,这里要注意输入栈和输出栈的关系。

在push数据的时候,只要数据放进输入栈就好,但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。

最后如何判断队列为空呢?如果进栈和出栈都为空的话,说明模拟的队列为空了。

代码

 1 class MyQueue {
 2 
 3     Stack<Integer> stackIn;
 4     Stack<Integer> stackOut;
 5 
 6     /** Initialize your data structure here. */
 7     public MyQueue() {
 8         stackIn = new Stack<>(); // 负责进栈
 9         stackOut = new Stack<>(); // 负责出栈
10     }
11     
12     /** Push element x to the back of queue. */
13     public void push(int x) {
14         stackIn.push(x);
15     }
16     
17     /** Removes the element from in front of queue and returns that element. */
18     public int pop() {    
19         dumpstackIn();
20         return stackOut.pop();
21     }
22     
23     /** Get the front element. */
24     public int peek() {
25         dumpstackIn();
26         return stackOut.peek();
27     }
28     
29     /** Returns whether the queue is empty. */
30     public boolean empty() {
31         return stackIn.isEmpty() && stackOut.isEmpty();
32     }
33 
34     // 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
35     private void dumpstackIn(){
36         if (!stackOut.isEmpty()) return; 
37         while (!stackIn.isEmpty()){
38                 stackOut.push(stackIn.pop());
39         }
40     }
41 }

 

225. 用队列实现栈

题目链接:225. 用队列实现栈 - 力扣(LeetCode)

题目

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

实现 MyStack 类:

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

注意:

你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
 

示例:

输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False

思路

队列模拟栈,其实一个队列就够了,那么我们先说一说两个队列来实现栈的思路。

队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并没有变成先进后出的顺序。

所以用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质。

但是依然还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全用来备份的!

用两个队列que1和que2实现队列的功能,que2其实完全就是一个备份的作用,把que1最后面的元素以外的元素都备份到que2,然后弹出最后面的元素,再把其他元素从que2导回que1。

注意:Java中Queue和Deque是接口,而非实现类

代码

使用两个Queue。

 1 class MyStack {
 2 
 3     Queue<Integer> queue1; // 和栈中保持一样元素的队列
 4     Queue<Integer> queue2; // 辅助队列
 5 
 6     /** Initialize your data structure here. */
 7     public MyStack() {
 8         queue1 = new LinkedList<>();
 9         queue2 = new LinkedList<>();
10     }
11     
12     /** Push element x onto stack. */
13     public void push(int x) {
14         queue2.offer(x); // 先放在辅助队列中
15         while (!queue1.isEmpty()){
16             queue2.offer(queue1.poll());
17         }
18         Queue<Integer> queueTemp;
19         queueTemp = queue1;
20         queue1 = queue2;
21         queue2 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中
22     }
23     
24     /** Removes the element on top of the stack and returns that element. */
25     public int pop() {
26         return queue1.poll(); // 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可
27     }
28     
29     /** Get the top element. */
30     public int top() {
31         return queue1.peek();
32     }
33     
34     /** Returns whether the stack is empty. */
35     public boolean empty() {
36         return queue1.isEmpty();
37     }
38 }

使用两个 Deque 实现

class MyStack {
    // Deque 接口继承了 Queue 接口
    // 所以 Queue 中的 add、poll、peek等效于 Deque 中的 addLast、pollFirst、peekFirst
    Deque<Integer> que1; // 和栈中保持一样元素的队列
    Deque<Integer> que2; // 辅助队列
    /** Initialize your data structure here. */
    public MyStack() {
        que1 = new ArrayDeque<>();
        que2 = new ArrayDeque<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        que1.addLast(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        int size = que1.size();
        size--;
        // 将 que1 导入 que2 ,但留下最后一个值
        while (size-- > 0) {
            que2.addLast(que1.peekFirst());
            que1.pollFirst();
        }

        int res = que1.pollFirst();
        // 将 que2 对象的引用赋给了 que1 ,此时 que1,que2 指向同一个队列
        que1 = que2;
        // 如果直接操作 que2,que1 也会受到影响,所以为 que2 分配一个新的空间
        que2 = new ArrayDeque<>();
        return res;
    }
    
    /** Get the top element. */
    public int top() {
        return que1.peekLast();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return que1.isEmpty();
    }
}

优化,使用一个Deque

 1 class MyStack {
 2 
 3     Queue<Integer> queue;
 4 
 5     public MyStack() {
 6         queue = new LinkedList<>();
 7     }
 8 
 9     //每 offer 一个数(A)进来,都重新排列,把这个数(A)放到队列的队首
10     public void push(int x) {
11         queue.offer(x);
12         int size = queue.size();
13         //移动除了 A 的其它数
14         while (size-- > 1)
15             queue.offer(queue.poll());
16     }
17 
18     public int pop() {
19         return queue.poll();
20     }
21 
22     public int top() {
23         return queue.peek();
24     }
25 
26     public boolean empty() {
27         return queue.isEmpty();
28     }
29 }

 

标签:队列,随想录,pop,que1,int,用栈,push,public
From: https://www.cnblogs.com/xpp3/p/17113769.html

相关文章