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中使用cookielib和urllib2配合PyQuery抓取网页信息
Apr 25 Python
Python中的ctime()方法使用教程
May 22 Python
Python计算三维矢量幅度的方法
Jun 15 Python
利用Python获取赶集网招聘信息前篇
Apr 18 Python
将Django项目部署到CentOs服务器中
Oct 18 Python
python类中super() 的使用解析
Dec 19 Python
使用 PyTorch 实现 MLP 并在 MNIST 数据集上验证方式
Jan 08 Python
python:批量统计xml中各类目标的数量案例
Mar 10 Python
python爬取网易云音乐热歌榜实例代码
Aug 07 Python
Python利用命名空间解析XML文档
Aug 10 Python
python爬虫基础之urllib的使用
Dec 31 Python
Pytorch之扩充tensor的操作
Mar 04 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
javascript+xml技术实现分页浏览
2008/07/27 Javascript
某页码显示的helper 少量调整,另附js版
2010/09/12 Javascript
jquery attr 设定src中含有&(宏)符号问题的解决方法
2011/07/26 Javascript
jquery遍历数组与筛选数组的方法
2013/11/05 Javascript
用javascript为页面添加天气显示实现思路及代码
2013/12/02 Javascript
鼠标经过tr时,改变tr当前背景颜色
2014/01/13 Javascript
js 获取元素在页面上的偏移量的方法汇总
2015/04/13 Javascript
基于jQuery实现淡入淡出效果轮播图
2020/07/31 Javascript
jQuery插件开发发送短信倒计时功能代码
2017/05/09 jQuery
JavaScript数据类型和变量_动力节点Java学院整理
2017/06/26 Javascript
vue.js中v-on:textInput无法执行事件问题的解决过程
2017/07/12 Javascript
详解Vue基于 Nuxt.js 实现服务端渲染(SSR)
2018/04/05 Javascript
vue中提示$index is not defined错误的解决方式
2020/09/02 Javascript
[02:43]中国五虎出征TI3视频
2013/08/02 DOTA
[01:07]2015国际邀请赛 中国区预选赛精彩回顾
2015/06/15 DOTA
Python图算法实例分析
2016/08/13 Python
如何利用Python分析出微信朋友男女统计图
2019/01/25 Python
python基础梳理(一)(推荐)
2019/04/06 Python
Python进阶:生成器 懒人版本的迭代器详解
2019/06/29 Python
python实现指定ip端口扫描方式
2019/12/17 Python
matplotlib制作雷达图报错ValueError的实现
2021/01/05 Python
python Scrapy爬虫框架的使用
2021/01/21 Python
简单的HTML5初步入门教程
2015/09/29 HTML / CSS
static全局变量与普通的全局变量有什么区别?static局部变量和普通局部变量有什么区别?static函数与普通函数有什么区别?
2015/02/22 面试题
师范应届生教师求职信
2013/11/05 职场文书
十月份红领巾广播稿
2014/01/22 职场文书
销售内勤岗位职责
2014/04/15 职场文书
《毛主席在花山》教学反思
2014/04/20 职场文书
企业宣传工作方案
2014/06/02 职场文书
会议邀请函
2015/01/30 职场文书
心术观后感
2015/06/11 职场文书
九年级语文教学反思
2016/03/03 职场文书
Python文件的操作示例的详细讲解
2021/04/08 Python
Python pandas读取CSV文件的注意事项(适合新手)
2021/06/20 Python
Spring整合Mybatis的全过程
2021/06/28 Java/Android
MySQL索引失效场景及解决方案
2022/07/23 MySQL