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


Posted in Python onNovember 01, 2017

本文实例讲述了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.data
class 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 = None
class 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 + result
t = 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中使用NLTK库实现对词干的提取的教程
Apr 08 Python
Python探索之修改Python搜索路径
Oct 25 Python
初探TensorFLow从文件读取图片的四种方式
Feb 06 Python
python实现决策树、随机森林的简单原理
Mar 26 Python
解决matplotlib库show()方法不显示图片的问题
May 24 Python
用python实现k近邻算法的示例代码
Sep 06 Python
Python实现深度遍历和广度遍历的方法
Jan 22 Python
Python写一个基于MD5的文件监听程序
Mar 11 Python
用Python画一个LinkinPark的logo代码实例
Sep 10 Python
Django DRF认证组件流程实现原理详解
Aug 17 Python
python 爬虫爬取京东ps4售卖情况
Dec 18 Python
Python一些基本的图像操作和处理总结
Jun 23 Python
Python栈算法的实现与简单应用示例
Nov 01 #Python
Python scikit-learn 做线性回归的示例代码
Nov 01 #Python
机器学习python实战之手写数字识别
Nov 01 #Python
Python定时器实例代码
Nov 01 #Python
机器学习python实战之决策树
Nov 01 #Python
详解Python开发中如何使用Hook技巧
Nov 01 #Python
python利用标准库如何获取本地IP示例详解
Nov 01 #Python
You might like
PHP面相对象中的重载与重写
2017/02/13 PHP
PHP读取并输出XML文件数据的简单实现方法
2017/12/22 PHP
PHP面向对象五大原则之开放-封闭原则(OCP)详解
2018/04/04 PHP
laravel框架实现为 Blade 模板引擎添加新文件扩展名操作示例
2020/01/25 PHP
模仿JQuery.extend函数扩展自己对象的js代码
2009/12/09 Javascript
Javascript倒计时代码
2010/08/12 Javascript
jquery 显示*天*时*分*秒实现时间计时器
2014/05/07 Javascript
jQuery控制TR显示隐藏的三种常用方法
2014/08/21 Javascript
JS返回iframe中frameBorder属性值的方法
2015/04/01 Javascript
基于jQuery实现的美观星级评论打分组件代码
2015/10/30 Javascript
jQuery+canvas实现简单的球体斜抛及颜色动态变换效果
2016/01/28 Javascript
jQuery查找节点并获取节点属性的方法
2016/09/09 Javascript
微信小程序中使元素占满整个屏幕高度实现方法
2016/12/14 Javascript
详解Vue.js项目API、Router配置拆分实践
2018/03/16 Javascript
详解三种方式在React中解决绑定this的作用域问题并传参
2020/08/18 Javascript
python实现发送邮件功能代码
2017/12/14 Python
pyqt5对用qt designer设计的窗体实现弹出子窗口的示例
2019/06/19 Python
Django Aggregation聚合使用方法解析
2019/08/01 Python
python-序列解包(对可迭代元素的快速取值方法)
2019/08/24 Python
解决Pycharm 包已经下载,但是运行代码提示找不到模块的问题
2019/08/31 Python
Django中间件拦截未登录url实例详解
2019/09/03 Python
解决pandas展示数据输出时列名不能对齐的问题
2019/11/18 Python
Ubuntu16安装Python3.9的实现步骤
2020/12/15 Python
手把手教你用纯css3实现轮播图效果实例
2017/05/04 HTML / CSS
CSS3中Animation动画属性用法详解
2016/07/04 HTML / CSS
SheIn沙特阿拉伯:女装在线
2020/03/23 全球购物
业务员岗位职责范本
2013/12/15 职场文书
公司人力资源的自我评价
2014/01/02 职场文书
学习交流会主持词
2014/04/01 职场文书
祖国在我心中演讲稿300字
2014/05/04 职场文书
企业党员一句话承诺
2014/05/30 职场文书
演讲比赛的活动方案
2014/08/28 职场文书
酒店前台辞职书
2015/02/26 职场文书
物业工程部经理岗位职责
2015/04/09 职场文书
工作简报格式范文
2015/07/21 职场文书
小学毕业教师寄语
2019/06/21 职场文书