LeetCode232:Implement Queue using 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.

Example:

MyQueue queue = new MyQueue();

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

Notes:

  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is emptyoperations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

LeetCode:链接

剑指offer同题:剑指Offer_编程题05:用两个栈实现队列

LeetCode镜像问题:LeetCode225:Implement Stack using Queues

需要两个栈Stack1和Stack2,push的时候直接push进Stack1。pop需要判断Stack1和Stack2中元素的情况,Stack2有值,直接从Stack2 pop,如果没有值,就把Stack1中的元素加入Stack2中,再进行pop。

和剑指offer不一样的是,多了peek和empty的操作。

class MyQueue(object):

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

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        self.queue.append(x)
        
    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        # 如果辅助栈为空 就要往里存数
        if not self.stack:
            while self.queue:
                self.stack.append(self.queue.pop())
        return self.stack.pop()
        

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

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        if self.stack or self.queue:
            return False
        else:
            return True
        
# 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()

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84886570