leetcode 232 using stack to realize queue

subject

Use the stack to implement the following operations of the queue:

  • push(x) -- put an element at the end of the queue.
  • pop() -- removes the element from the head of the queue.
  • peek() -- returns the element at the beginning of the queue.
  • empty() -- returns whether the queue is empty.

Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek(); / / return 1
 queue.pop(); / / return 1
 queue.empty(); / / return false

Explain:

  • You can only use standard stack operations -- that is, only push to top, peek/pop from top, size, and is empty operations are legal.
  • The language you use may not support stacks. You can use list or deque to simulate a stack, as long as it is a standard stack operation.
  • Assume that all operations are valid (for example, an empty queue does not call a pop or peek operation).

Code

class MyQueue(object):

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

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

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        if not self.s2:
            self.s2 = self.s1
            self.s2.reverse()
            self.s1 = []
        removed_ele = self.s2[-1]    
        self.s2 = self.s2[:-1]
        return removed_ele

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        if self.s1:
            return self.s1[0]
        else:
            return self.s2[-1]

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


# 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()

Summary: use python list structure to simulate stack.

Tags: Python

Posted on Fri, 08 Nov 2019 12:14:45 -0800 by Huntress