Implement Queue with stacks

题目描述

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

解题方法

用两个stack

  • Push时,push到stack1上
  • 当pop或top时,将stack1的都pop到stack2上,此时stack2的top就是最早的

Solution

class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack1 = []
        self.stack2 = []

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

    def pop(self):
        """
        :rtype: nothing
        """
        if not self.stack2:
            while self.stack1:
                ele = self.stack1.pop()
                self.stack2.append(ele)
        return self.stack2.pop()

    def peek(self):
        """
        :rtype: int
        """
        if not self.stack2:
            while self.stack1:
                ele = self.stack1.pop()
                self.stack2.append(ele)
        return self.stack2[-1]

    def empty(self):
        """
        :rtype: bool
        """
        if not self.stack1 and not self.stack2:
            return True
        else:
            return False

Reference