【Leetcode-python】栈和队列题II

本文探讨了使用双向列表实现队列和栈的数据结构方法。通过对比两种实现方式,详细解析了其内部工作原理,包括push、pop、top和empty等关键操作的效率分析。

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

class MyStack(object):
    """
    双向列表实现,为什么push时候使用q更快?此方法36ms,注释方法20ms
    """
    def __init__(self):
        self._queue = collections.deque()

    def push(self, x):
        # q = self._queue
        # q.append(x)
        # for _ in range(len(q) - 1):
        #     q.append(q.popleft())
        self._queue.append(x)
        for _ in range(len(self._queue) - 1):
            self._queue.append(self._queue.popleft())

    def pop(self):
        return self._queue.popleft()

    def top(self):
        return self._queue[0]

    def empty(self):
        return not len(self._queue)

 

class MyQueue(object):
    """
    思路:利用两个stack实现。
    push:直接存入stack_1中
    pop:由于stack_1 pop栈顶元素(即后进入的元素),故将stack_1元素存入stack_2中,此时
    stack_2栈顶为先进入的元素,pop即实现先进先出
    peek:此时需要思考清楚,到底哪个是队首元素
    假设如果我们没进行pop操作,则只有stack_1有元素,队首stack[0]
    但是进行了pop操作,则队首元素一定在stack_2,且在栈顶stack[-1]
    看了一下别人的方法,大同小异
    """
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack_1,self.stack_2 = [],[]


    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        self.stack_1.append(x)

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        self.peek()
        return self.stack_2.pop()
        """
        if self.stack_2 is None:
            while self.stack_1:
                self.stack_2.append(self.stack_1.pop())
        res = self.stack_2.pop()
        return res


    def peek(self):
        """
        Get the front element.
        :rtype: int
        if not self.stack_2:
            while self.stack_1:
                self.stack_2.append(self.stack_1.pop())
        return self.stack_2[-1]
        """
        return self.stack_1[0]


    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return not self.stack_1 and not self.stack_2

# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值