侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python编程实现双链表,栈,队列及二叉树的方法示例

Python  /  管理员 发布于 7年前   333

本文实例讲述了Python编程实现双链表,栈,队列及二叉树的方法。分享给大家供大家参考,具体如下:

1.双链表

class Node(object):  def __init__(self, value=None):    self._prev = None    self.data = value    self._next = None  def __str__(self):    return "Node(%s)"%self.dataclass DoubleLinkedList(object):  def __init__(self):    self._head = Node()  def insert(self, value):    element = Node(value)    element._next = self._head    self._head._prev = element    self._head = element  def search(self, value):    if not self._head._next:      raise ValueError("the linked list is empty")    temp = self._head    while temp.data != value:      temp = temp._next    return temp  def delete(self, value):    element = self.search(value)    if not element:      raise ValueError('delete error: the value not found')    element._prev._next = element._next    element._next._prev = element._prev    return element.data  def __str__(self):    values = []    temp = self._head    while temp and temp.data:      values.append(temp.data)      temp = temp._next    return "DoubleLinkedList(%s)"%values

2. 栈

class Stack(object):  def __init__(self):    self._top = 0    self._stack = []  def put(self, data):    self._stack.insert(self._top, data)    self._top += 1  def pop(self):    if self.isEmpty():      raise ValueError('stack 为空')    self._top -= 1    data = self._stack[self._top]    return data  def isEmpty(self):    if self._top == 0:      return True    else:      return False  def __str__(self):    return "Stack(%s)"%self._stack

3.队列

class Queue(object):  def __init__(self, max_size=float('inf')):    self._max_size = max_size    self._top = 0    self._tail = 0    self._queue = []  def put(self, value):    if self.isFull():      raise ValueError("the queue is full")    self._queue.insert(self._tail, value)    self._tail += 1  def pop(self):    if self.isEmpty():      raise ValueError("the queue is empty")    data = self._queue.pop(self._top)    self._top += 1    return data  def isEmpty(self):    if self._top == self._tail:      return True    else:      return False  def isFull(self):    if self._tail == self._max_size:      return True    else:      return False  def __str__(self):    return "Queue(%s)"%self._queue

4. 二叉树(定义与遍历)

class Node:  def __init__(self,item):    self.item = item    self.child1 = None    self.child2 = Noneclass Tree:  def __init__(self):    self.root = None  def add(self, item):    node = Node(item)    if self.root is None:      self.root = node    else:      q = [self.root]      while True:        pop_node = q.pop(0)        if pop_node.child1 is None:          pop_node.child1 = node          return        elif pop_node.child2 is None:          pop_node.child2 = node          return        else:          q.append(pop_node.child1)          q.append(pop_node.child2)  def traverse(self): # 层次遍历    if self.root is None:      return None    q = [self.root]    res = [self.root.item]    while q != []:      pop_node = q.pop(0)      if pop_node.child1 is not None:        q.append(pop_node.child1)        res.append(pop_node.child1.item)      if pop_node.child2 is not None:        q.append(pop_node.child2)        res.append(pop_node.child2.item)    return res  def preorder(self,root): # 先序遍历    if root is None:      return []    result = [root.item]    left_item = self.preorder(root.child1)    right_item = self.preorder(root.child2)    return result + left_item + right_item  def inorder(self,root): # 中序序遍历    if root is None:      return []    result = [root.item]    left_item = self.inorder(root.child1)    right_item = self.inorder(root.child2)    return left_item + result + right_item  def postorder(self,root): # 后序遍历    if root is None:      return []    result = [root.item]    left_item = self.postorder(root.child1)    right_item = self.postorder(root.child2)    return left_item + right_item + resultt = Tree()for i in range(10):  t.add(i)print('层序遍历:',t.traverse())print('先序遍历:',t.preorder(t.root))print('中序遍历:',t.inorder(t.root))print('后序遍历:',t.postorder(t.root))

输出结果:

层次遍历: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]先次遍历: [0, 1, 3, 7, 8, 4, 9, 2, 5, 6]中次遍历: [7, 3, 8, 1, 9, 4, 0, 5, 2, 6]后次遍历: [7, 8, 3, 9, 4, 1, 5, 6, 2, 0]

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    python 简单搭建阻塞式单进程,多进程,多线程服务的实例
    下一条:
    Python栈算法的实现与简单应用示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客