Implement Stack using Queues

本文探讨了如何使用队列实现栈的基本操作,包括push、pop、top和empty,并提供了两种实现方式,一种为O(1)的push操作,但pop、top和empty为O(n);另一种则使pop和top操作达到O(1),但push和empty为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这题是使用队列去实现栈,属于比较基础的题目。需要考虑的点在于队列为先进先出,即入队在队尾,但是出队在队首,而栈为先进后出,即出栈和入栈都在栈尾。需要实现的功能如下:

push(x) -- Push element x onto stack.

pop() -- Removes the element on top of the stack.

top() -- Get the top element.

empty() -- Return whether the stack is empty.

我的解法一,python使用collections.deque()

class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.queue = collections.deque()
        

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.queue.append(x)

    def pop(self):
        """
        :rtype: nothing
        """
        i = len(self.queue)-1
        while i > 0:
            self.queue.append(self.queue.popleft())
            i-=1
        self.queue.popleft()
            

    def top(self):
        """
        :rtype: int
        """
        size=len(self.queue)
        return self.queue[size-1]
        

    def empty(self):
        """
        :rtype: bool
        """
        return len(self.queue)==0
        

这种解法其中push复杂度为O(1),pop,top,empty复杂度都为为O(n),属于比较不理想的解法。

参考一些优质解法,一个非常巧妙的思路逆序存储。具体做法为:在push元素之后,对queue中已有的元素做一个queue长度n-1次的右旋转, 相当于rotate(len(queue)-1),相当于将该元素插入在了队首。而从一开始push()就如此操作,相当于每次push之后,queue中的元素都保持原有的元素的逆序。从而使pop和top操作都为O(1),只有empty和push操作都为O(n).代码如下:

class Stack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.queue = collections.deque()
        

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.queue.append(x)
        i=len(self.queue)-1
        while i > 0:
            self.queue.append(self.queue.popleft())
            i-=1

    def pop(self):
        """
        :rtype: nothing
        """
        self.queue.popleft()
            

    def top(self):
        """
        :rtype: int
        """
        return self.queue[0]
        

    def empty(self):
        """
        :rtype: bool
        """
        return len(self.queue)==0

 

转载于:https://www.cnblogs.com/sherylwang/p/5373017.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值