LeetCode-Python-225. Implementing stacks with queues

Keywords: network

Queues are used to implement the following operations on the stack:

push(x) -- Element x is stacked
pop() -- Remove the top element of the stack
top() -- Gets the top element of the stack
empty() -- Whether the return stack is empty
Be careful:

You can only use the basic operations of the queue -- push to back, peek/pop from front, size, and is empty -- which are legal.
The language you use may not support queues. You can use list or deque to simulate a queue as long as it is a standard queue operation.
You can assume that all operations are valid (for example, pop or top operations are not invoked on an empty stack).

Source: LeetCode
Link: https://leetcode-cn.com/problems/implementation-stack-use-queues
Copyright belongs to the seizure network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Ideas:

The queue is FIFO and the stack is FIFO.

To implement the stack with a queue, you can invert two queues to each other.

class MyStack(object):

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

    def push(self, x):
        """
        Push element x onto stack.
        :type x: int
        :rtype: None
        """
        self.queue1.append(x)

        while len(self.queue1) > 1:
            self.queue2.append(self.queue1[0])
            self.queue1 = self.queue1[1:]

            
        # print self.queue1, self.queue2
    def pop(self):
        """
        Removes the element on top of the stack and returns that element.
        :rtype: int
        """
        # print self.queue1, self.queue2
        top = self.queue1[0]
        self.queue1, self.queue2 = self.queue2, []
        while len(self.queue1) > 1:
            self.queue2.append(self.queue1[0])
            self.queue1 = self.queue1[1:]
        return top
            

    def top(self):
        """
        Get the top element.
        :rtype: int
        """
        return self.queue1[0]
        
    def empty(self):
        """
        Returns whether the stack is empty.
        :rtype: bool
        """
        return not self.queue1 and not self.queue2


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

 

Posted by lakilevi on Wed, 09 Oct 2019 10:15:35 -0700