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爬虫之抓取百度贴吧并存储到本地txt文件改进版
Nov 06 Python
python logging日志模块的详解
Oct 29 Python
基于Python中单例模式的几种实现方式及优化详解
Jan 09 Python
解决Python的str强转int时遇到的问题
Apr 09 Python
Python实现绘制双柱状图并显示数值功能示例
Jun 23 Python
Python爬虫的两套解析方法和四种爬虫实现过程
Jul 20 Python
pygame游戏之旅 计算游戏中躲过的障碍数量
Nov 20 Python
Python中的heapq模块源码详析
Jan 08 Python
详解pandas如何去掉、过滤数据集中的某些值或者某些行?
May 15 Python
python多线程共享变量的使用和效率方法
Jul 16 Python
Python+Selenium+phantomjs实现网页模拟登录和截图功能(windows环境)
Dec 11 Python
python 多线程中join()的作用
Oct 29 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 调试环境(IIS+PHP+MYSQL)
2007/01/10 PHP
PHP实现的连贯操作、链式操作实例
2014/07/08 PHP
Laravel 5框架学习之Eloquent (laravel 的ORM)
2015/04/08 PHP
php创建多级目录与级联删除文件的方法示例
2019/09/12 PHP
一组JS创建和操作表格的函数集合
2009/05/07 Javascript
javascript控制swfObject应用介绍
2012/11/29 Javascript
JS、CSS加载中的小问题探讨
2013/11/26 Javascript
JavaScript使用HTML5的window.postMessage实现跨域通信例子
2014/04/11 Javascript
javascript中with()方法的语法格式及使用
2014/08/04 Javascript
nodejs开发微博实例
2015/03/25 NodeJs
JQuery使用$.ajax和checkbox实现下次不在通知功能
2015/04/16 Javascript
javascript中mouseover、mouseout使用详解
2015/07/19 Javascript
Bootstrap里的文件分别代表什么意思及其引用方法
2017/05/01 Javascript
JS基于封装函数实现的表格分页完整示例
2018/06/26 Javascript
[46:03]LGD vs VGJ.T 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
python根据时间生成mongodb的ObjectId的方法
2015/03/13 Python
自己使用总结Python程序代码片段
2015/06/02 Python
Python中random模块生成随机数详解
2016/03/10 Python
Python处理json字符串转化为字典的简单实现
2016/07/07 Python
Django原生sql也能使用Paginator分页的示例代码
2017/11/15 Python
python+pygame简单画板实现代码实例
2017/12/13 Python
Python从单元素字典中获取key和value的实例
2018/12/31 Python
python 利用pywifi模块实现连接网络破解wifi密码实时监控网络
2019/09/16 Python
8段用于数据清洗Python代码(小结)
2019/10/31 Python
浅谈SciPy中的optimize.minimize实现受限优化问题
2020/02/29 Python
如何打包Python Web项目实现免安装一键启动的方法
2020/05/21 Python
Python利用imshow制作自定义渐变填充柱状图(colorbar)
2020/12/10 Python
美国护肤咨询及美容产品电商:Askderm
2017/02/24 全球购物
乐天旅游香港网站:日本饭店预订
2017/11/29 全球购物
学院书画协会部门职责
2013/11/28 职场文书
爱国卫生月实施方案
2014/02/21 职场文书
学习“七一”讲话精神体会
2014/07/08 职场文书
教师作风整改措施思想汇报
2014/10/12 职场文书
2015试用期转正工作总结
2014/12/12 职场文书
行政文员岗位职责
2015/02/04 职场文书
七年级上册生物的课件
2019/08/07 职场文书