zoukankan      html  css  js  c++  java
  • python实现stack(栈)和队列(queue)

    栈是先进后出 队列先进先出
    栈示意图(顺便治治颈椎):
    在这里插入图片描述
    队列示意图:
    在这里插入图片描述
    栈实现代码:

    class Stack(object):
        def __init__(self):
            self.stack = []
    
        def push(self, v):
            self.stack.append(v)
    
        def pop(self):
            if self.stack:
                # 推出栈
                return self.stack.pop()
            else:
                raise LookupError("stack is empty")
    
        def is_empty(self):
            return bool(self.stack)
    
        def top(self):
            return self.stack[-1]
    

    队列实现代码:

    
    
    class Head(object):
        def __init__(self):
            self.right = None
            self.left = None
    
    
    class Node(object):
        def __init__(self, value):
            self.value = value
            self.next = None
    
    
    class Queue(object):
        def __init__(self):
            self.head = Head()
    
        def queue(self, value):
            new_node = Node(value)
            head = self.head
            if head.right:
                tmp = head.right
                head.right = new_node
                tmp.next = new_node
            else:
                head.left = head.right = new_node
    
        def dequeue(self):
            if self.is_empty():
                raise LookupError('Queue is empty')
            head = self.head
            tmp = head.left
            if head.left == head.right:
                head.left = head.right = None
            else:
                head.left = tmp.next
            return tmp.value
    
        def is_empty(self):
            return not bool(self.head.left)
    
        def top(self):
            if self.is_empty():
                raise LookupError('Queue is empty')
            return self.head.left.value
    

    希望能交流更多技术,关注小白的微信公众号吧。
    在这里插入图片描述

    小白技术社
  • 相关阅读:
    面向对象概述(课堂笔记)
    final
    static方法
    Ubuntu中Qt5.7.0无法输入中文
    Ubuntu中Qt+opencv图像显示
    Ubuntu中Qt新建窗体提示lGL错误
    Ubuntu中Qt5.7.0的安装及opencv2.4.13配置
    Ubuntu16.04删除客人会话
    ffmpeg的安装--opencv视频处理必备
    CentOS+OpenCV图像的读入、显示
  • 原文地址:https://www.cnblogs.com/xbjss/p/13326675.html
Copyright © 2011-2022 走看看