leetcode 225. 用队列实现栈(python)

在这里插入图片描述
题解:

  1. 对于队列,是先进先出;对于栈,是先进后出,两者在元素出去的位置地方正好相反,因此我们需要用队列实现后进元素先出去的效果;
    乍一想,我们需要实现队列内元素的反转操作,
    但是此题的解题思想并没有完全实现反转,只是把队列的最后一个元素,移动到队头即可;这样就可以实现和栈相同的效果(后进先出);
  2. 即我们需要实现队头元素为栈底元素。

方法一:我们首选利用双队列来进行实现:
基本思想如下:
在队列的入队过程中实现:(假设当前入队元素为x)

  1. 我们利用两个队列queue和help来实现;queue是主队列,help是辅助队列;
  2. 对于queue我们一直出队元素,直到为空,其中出队的元素按序装进help队列中;
  3. 然后queue此时为空,我们再进队当前需要入队的元素x,因为此时queue为空,所以当前进队元素x就变成了队头(对于栈来说,就是栈底的那个元素);并且此时在队列中会优先出队,因此我们相当于实现了栈的后进先出。
  4. 之后再从help队列中把元素再复制进来即可。
    代码如下:
class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue = []
        self.help = []


    def push(self, x):
        """
        Push element x onto stack.
        """

        while len(self.queue) > 0:

            self.help.append(self.queue.pop(0))

        self.queue.append(x)

        while len(self.help) > 0:

            self.queue.append(self.help.pop(0))

    def pop(self) :
        """
        Removes the element on top of the stack and returns that element.
        """

        de = self.queue.pop(0)
        return de

    def top(self):
        """
        Get the top element.
        """
        de = self.queue[0]
        return de

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        if len(self.queue) == 0:
            return True
        return False

方法二:单队列实现:
基本思想

  1. 在队列中push过程中实现;
  2. 首先在队列中进入当前元素x;
  3. 然后获取当前队列的长度length;
  4. 最后把队列按照顺序出队,出队的元素再重新进入当前队列,每出队一个元素,length的值减少一;直到length的长度为1,不再出队;此时队列的头元素就是元素x;这样在pop的过程中就实现了后进先出的效果。

代码如下:

class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue = []
        

    def push(self, x):
        """
        Push element x onto stack.
        """

        self.queue.append(x)

        length = len(self.queue)

        while length > 1:

            self.queue.append(self.queue.pop(0))
            length -= 1


    def pop(self) :
        """
        Removes the element on top of the stack and returns that element.
        """

        de = self.queue.pop(0)
        return de



    def top(self):
        """
        Get the top element.
        """
        de = self.queue[0]
        return de

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        if len(self.queue) == 0:
            return True
        return False
发布了100 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/cy_believ/article/details/104612729