研习代码 day9 | 双栈实现队列 && 双队列实现栈

一、用栈实现队列

        1.1 题目

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

实现 MyQueue 类:

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

说明:

  • 你 只能 使用标准的栈操作 —— 也就是只有 push to toppeek/pop from topsize, 和 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

提示:

  • 1 <= x <= 9
  • 最多调用 100 次 pushpoppeek 和 empty
  • 假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)

进阶:

  • 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。

        1.2 题目链接

        232.用栈实现队列

        1.3 解题思路和过程想法

        (1)解题思路 

        使用双栈(列表)实现一个队列:一个输入栈,一个输出栈。前者将输入顺序颠倒,后者将输入顺序再次颠倒,负负得正,最终得到正序。

        (2)过程想法

        思考的过程比较自然,或许因为简单吧。

        1.4 代码

class MyQueue:
    # 使用双栈实现一个队列:一个输入栈,一个输出栈,
    # 前者将输入顺序颠倒,后者将输入顺序再次颠倒,负负得正,最终得到正序

    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, x: int) -> None:
        self.stack1.append(x)

    def pop(self) -> int:
        # 若输出栈为空,需先导入输入栈的元素;否则直接弹出输出栈的元素
        if len(self.stack2) == 0:
            while len(self.stack1):
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()

    def peek(self) -> int:
        # 若输出栈为空,需先导入输入栈的元素;否则直接返回输出栈的元素
        if len(self.stack2) == 0:
            while len(self.stack1):
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]

    def empty(self) -> bool:
        if len(self.stack1) or len(self.stack2):
            return False
        else:
            return True

二、用队列实现栈

        2.1 题目

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

实现 MyStack 类:

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

注意:

  • 你只能使用队列的基本操作 —— 也就是 push to backpeek/pop from frontsize 和 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

提示:

  • 1 <= x <= 9
  • 最多调用100 次 pushpoptop 和 empty
  • 每次调用 pop 和 top 都保证栈不为空

进阶:你能否仅用一个队列来实现栈。

        2.2 题目链接

        225.用队列实现栈

        2.3 解题思路和过程想法

       (1) 解题思路:

        用双队列实现栈,workQueue 用于存放数据,tempQueue 用于中转数据的暂存。为实现先进后出,将 workQueue 的 n-1 个元素输入到 tempQueue 中,输出 workQueue 最后一个元素,最后将 workQueue 与 tempQueue 交换,始终保持仅有 workQueue 存有元素。

        (2)过程想法:

        大多用 deque 来实现,因其既具有队列又具有栈的特性,但我觉得这道题主要想考察的是如何利用两个队列来实现栈的特性,所以我用的双栈。思路不像用双栈实现队列(可以负负得正),只能再用一个队列作为倒腾的暂存空间。

        2.4 代码

from queue import Queue

class MyStack:
    # 用两队列实现栈,workQueue 用于存放数据,tempQueue 用于中转数据的暂存容器

    def __init__(self):
        self.workQueue = Queue()
        self.tempQueue = Queue()

    def push(self, x: int) -> None:
        self.workQueue.put(x)

    def pop(self) -> int:
        # 将 workQueue 的 n-1 个元素输入到 tempQueue 中,输出 workQueue 最后一个元素
        # 并将 workQueue 与 tempQueue 交换,始终保持仅有 workQueue 存有元素
        while self.workQueue.qsize() - 1:
            self.tempQueue.put(self.workQueue.get()) 
        num = self.workQueue.get()
        self.workQueue, self.tempQueue = self.tempQueue,self.workQueue
        return num        

    def top(self) -> int:
        # 将 workQueue 的所有元素输入到 tempQueue 中,并输出 workQueue 最后一个元素
        # 并将 workQueue 与 tempQueue 交换,始终保持仅有 workQueue 存有元素
        num = 0
        while self.workQueue.qsize():
            num = self.workQueue.get()
            self.tempQueue.put(num) 
        self.workQueue, self.tempQueue = self.tempQueue,self.workQueue
        return num

    def empty(self) -> bool:
        return self.workQueue.empty()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值