LeetCode-232 用栈实现队列---Python代码实现及详解

题目:

使用栈实现队列的下列操作:

push(x) -- 将一个元素放入队列的尾部。

pop() -- 从队列首部移除元素。

peek() -- 返回队列首部的元素。

empty() -- 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();

queue.push(1);

queue.push(2);

queue.peek(); // 返回 1

queue.pop(); // 返回 1

queue.empty(); // 返回 false

说明:

你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。

你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

 

思路:

       栈是后进先出,队列是先进先出,一个栈是无法解决这道题的。可以使用两个栈,先把数据放入一个栈中然后再依次取出放入到另一个栈中,如:队列是 1->2->3, 使用栈实现,先用栈a 存放1->2->3,然后再导入到另一个栈 b中,因为栈是后进先出所以栈b为 3->2->1。栈b 不为空直接pop,否则把栈a 的所有元素放到栈b 然后执行栈b的 pop操作。push操作只需要向栈a中push就行。

from collections import deque

class Stack:   
    '''实现栈结构,先进后出'''
    def __init__(self):
        self.items = deque()
    
    def push(self, val):
        return self.items.append(val)
    
    def pop(self):
        return self.items.pop()
    
    def top(self):  # 返回栈顶值,双端队列右边作为栈顶
        return self.items[-1]
    
    def empty(self):
        return len(self.items) == 0
    
    
class MyQueue:
    '''使用栈实现队列操作'''
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.s1 = Stack()
        self.s2 = Stack()
        

    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.s1.push(x)
        

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if not self.s2.empty():  # 只要栈s2不为空直接返回栈s2中元素
            return self.s2.pop()
        while not self.s1.empty():     # 将栈s1的元素转到s2中
            val = self.s1.pop()
            self.s2.push(val)
        return self.s2.pop()
        

    def peek(self) -> int:
        """
        Get the front element.
        """
        if not self.s2.empty():
            return self.s2.top()
        while not self.s1.empty():
            val = self.s1.pop()
            self.s2.push(val)
        return self.s2.top()
        

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return self.s1.empty() and self.s2.empty()


def test():         # 我自己写的本地测试代码,可以不要
	q = MyQueue()
	q.push(1)
	q.push(2)
	q.push(3)
	print(q.pop())
	print(q.pop())
	print(q.pop())

test()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值