美文网首页
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. 用栈实现队列

    难度:中等 1. Description 2. Solution python用两个栈,十分巧妙。 3. Refe...

  • 40. 用栈实现队列

    40. 用栈实现队列 描述 笔记 数据 评测 正如标题所述,你需要使用两个栈来实现队列的一些操作。 队列应支持pu...

  • lintcode 用栈实现队列

    正如标题所述,你需要使用两个栈来实现队列的一些操作。队列应支持push(element),pop() 和 top(...

  • 数据结构——栈和队列

    用数组实现栈和队列 用栈实现队列 用队列实现栈 栈和队列的经典算法题最小间距栈宠物收养所 数组实现栈和队列 用数组...

  • 40. 用栈实现队列

    描述 正如标题所述,你需要使用两个栈来实现队列的一些操作。队列应支持push(element),pop() 和 t...

  • leecode刷题(26)-- 用栈实现队列

    leecode刷题(26)-- 用栈实现队列 用栈实现队列 使用栈实现队列的下列操作: push(x) -- 将一...

  • C语言第七次作业:链表

    707. 设计链表 空指针 空节点 225. 用队列实现栈 链式存储栈 双队列实现栈 232. 用栈实现队列 链式...

  • 队列之-队列实现栈

    一、队列实现栈核心算法概述 之前已经描述过了用栈实现队列的功能,见栈系列之-实现队列,那么同样队列也可以用来实现栈...

  • 38_两个有趣的问题

    关键词:通过栈实现队列、通过队列实现栈 0. 通过栈实现队列 用栈实现队列等价于用后进先出的特性实现先进先出的特性...

  • 栈&队列

    一、栈&队列总结 栈/队列的应用接雨水验证栈序列滑动窗口的最大值 栈/队列的特殊实现用两个栈实现队列用两个队列实现...

网友评论

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

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