美文网首页
lintcode 40. 用栈实现队列

lintcode 40. 用栈实现队列

作者: cuizixin | 来源:发表于2018-08-31 21:48 被阅读1次

    难度:中等

    1. Description

    40. 用栈实现队列

    2. Solution

    • python
      用两个栈,十分巧妙。
    class MyQueue:
        
        def __init__(self):
            # do intialization if necessary
            self.stack1 = []
            self.stack2 = []
        
        def adjust(self):
            if len(self.stack2)==0:
                while len(self.stack1)>0:
                    self.stack2.append(self.stack1.pop())
    
        """
        @param: element: An integer
        @return: nothing
        """
        def push(self, element):
            # write your code here
            self.stack1.append(element)
    
        """
        @return: An integer
        """
        def pop(self):
            # write your code here
            self.adjust()
            return self.stack2.pop()
    
        """
        @return: An integer
        """
        def top(self):
            # write your code here
            self.adjust()
            return self.stack2[-1]
    

    3. Reference

    1. https://www.lintcode.com/problem/implement-queue-by-two-stacks/?_from=ladder

    相关文章

      网友评论

          本文标题:lintcode 40. 用栈实现队列

          本文链接:https://www.haomeiwen.com/subject/howewftx.html