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实现简单的语音识别系统
Dec 13 Python
Python求解任意闭区间的所有素数
Jun 10 Python
python远程连接服务器MySQL数据库
Jul 02 Python
Python中xml和json格式相互转换操作示例
Dec 05 Python
详解Python Matplot中文显示完美解决方案
Mar 07 Python
Python中使用pypdf2合并、分割、加密pdf文件的代码详解
May 21 Python
selenium处理元素定位点击无效问题
Jun 12 Python
详解python中的生成器、迭代器、闭包、装饰器
Aug 22 Python
Python 下载及安装详细步骤
Nov 04 Python
python GUI库图形界面开发之PyQt5信号与槽的高级使用技巧装饰器信号与槽详细使用方法与实例
Mar 06 Python
Python 内存管理机制全面分析
Jan 16 Python
Python实现GIF动图以及视频卡通化详解
Dec 06 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模板,主要想体现一下思路
2006/12/25 PHP
PHP+Memcache实现wordpress访问总数统计(非插件)
2014/07/04 PHP
php中的ini配置原理详解
2014/10/14 PHP
php简单获取复选框值的方法
2016/05/11 PHP
PHP生成word文档的三种实现方式
2016/11/14 PHP
PHP实现动态获取函数参数的方法示例
2018/04/02 PHP
jQuery 删除/替换DOM元素的几种方式
2014/05/20 Javascript
jquery操作checked属性以及disabled属性的多种方法
2014/06/20 Javascript
JavaScript字符串对象toUpperCase方法入门实例(用于把字母转换为大写)
2014/10/17 Javascript
动态加载js的方法汇总
2015/02/13 Javascript
关于HTTP传输中gzip压缩的秘密探索分析
2018/01/12 Javascript
浅谈Node.js 沙箱环境
2018/05/15 Javascript
JS判断字符串是否为整数的方法--简单的正则判断
2018/07/23 Javascript
深入理解Vue.js轻量高效的前端组件化方案
2018/12/10 Javascript
Vue router传递参数并解决刷新页面参数丢失问题
2020/12/02 Vue.js
Python实现的简单排列组合算法示例
2018/07/04 Python
详解Python3 基本数据类型
2019/04/19 Python
python控制nao机器人身体动作实例详解
2019/04/29 Python
对Python 简单串口收发GUI界面的实例详解
2019/06/12 Python
Python从文件中读取指定的行以及在文件指定位置写入
2019/09/06 Python
Python大数据之从网页上爬取数据的方法详解
2019/11/16 Python
python实现差分隐私Laplace机制详解
2019/11/25 Python
关于tf.matmul() 和tf.multiply() 的区别说明
2020/06/18 Python
Python classmethod装饰器原理及用法解析
2020/10/17 Python
python3.9和pycharm的安装教程并创建简单项目的步骤
2021/02/03 Python
利用Storage Event实现页面间通信的示例代码
2018/07/26 HTML / CSS
公关关系专员的自我评价分享
2013/11/20 职场文书
二手书店创业计划书
2014/01/16 职场文书
临床护士自荐信
2014/01/31 职场文书
企业军训感想
2014/02/07 职场文书
《开国大典》教学反思
2014/04/19 职场文书
2015年店长工作总结范文
2015/04/08 职场文书
2016年党课培训学习心得体会
2016/01/07 职场文书
教师外出学习心得体会
2016/01/18 职场文书
如何拟写通知正文?
2019/04/02 职场文书
《进击的巨人》新联动CM 兵长强势出击兽巨人
2022/04/05 日漫