zoukankan      html  css  js  c++  java
  • Python实现栈、队列、双端队列

    栈的实现

    class Stack():
        def __init__(self):
            self.items = []
    
        def push(self, item):
            self.items.append(item)
    
        def pop(self):
            return self.items.pop()
    
        def peek(self):
            return self.items[len(self.items)-1]
    
        def isEmpty(self):
            return len(self.items) == 0
    
        def size(self):
            return len(self.items)
    
    stack=Stack()
    stack.push(1)
    stack.push(2)
    stack.push(3)
    print(stack.peek())
    print(stack.pop())
    print(stack.pop())
    print(stack.pop())

    队列的实现

    #coding:utf8
    class Queue():
        def __init__(self):
            self.items = []
    
        def enqueue(self, item):
            self.items.insert(0, item)
    
        def dequeue(self):
            return self.items.pop()
    
        def isEmpty(self):
            return len(self.items) == 0
    
        def size(self):
            return len(self.items)
    
    # queue = Queue()
    # queue.enqueue(1)
    # queue.enqueue(2)
    # queue.enqueue(3)
    # print(queue.size())
    # print(queue.dequeue())
    # print(queue.dequeue())
    # print(queue.dequeue())

    队列算法之烫手的山芋

    kids = ["A", "B", "C", "D", "E", "F"]  # 参加游戏的孩子
    queue = Queue()
    for kid in kids:
        queue.enqueue(kid)
    while queue.size() > 1:
        for i in range(6):
            queue.enqueue(queue.dequeue())
        queue.dequeue()
    print(queue.dequeue())

    双端队列的实现

    # coding:utf8
    # 队列  :尾部--->首部
    class Deque():
        def __init__(self):
            self.items = []
    
        def addFront(self, item):
            self.items.append(item)
    
        def addRear(self, item):
            return self.items.insert(0, item)
    
        def removeFront(self):
            return self.items.pop()
    
        def removeRear(self):
            return self.items.pop(0)
    
        def isEmpty(self):
            return len(self.items) == 0
    
        def size(self):
            return len(self.items)

    双端队列算法之回文检测

    # 实现回文检查
    def isHuiWen(_str):
        flag = True
        deque = Deque()
        for i in _str:
            deque.addFront(i)
        while deque.size() > 1:
            if deque.removeFront() != deque.removeRear():
                flag = False
                break
        return flag
    
    
    print(isHuiWen("hooh"))
    print(isHuiWen("hoioh"))
    print(isHuiWen("hoijoh"))
  • 相关阅读:
    CentOS下NFS服务器安装及配置实例
    appserver安装常见的问题
    java程序链接到sql server数据库
    用C# ASP.net将数据库中的数据表导出到Excel中
    看 《精通CSS》 的读书笔记
    CSS 布局练习
    CSS 学习&测试记录
    兼容 IE6 下Tbody 的 innerHTML 只读无法赋值的问题
    IE6 中 select 隐藏不了的问题
    setInterval、ajax 并用引发的内存漏泄
  • 原文地址:https://www.cnblogs.com/sun-10387834/p/12815215.html
Copyright © 2011-2022 走看看