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

 更新时间:2017年11月01日 12:00:45   作者:王辉_Python  
这篇文章主要介绍了Python编程实现双链表,栈,队列及二叉树的方法,结合具体实例形式分析了Python简单实现数据结构中双链表,栈,队列及二叉树相关操作技巧,需要的朋友可以参考下

本文实例讲述了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加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

  • Python十大列表操作技巧分享

    Python十大列表操作技巧分享

    这篇文章给大家介绍了Python十大列表操作技巧分享,列表展开,降维,分块,转置,查找众数,判断重复元素等十个操作技巧,并通过代码示例给大家介绍的非常详细,需要的朋友可以参考下
    2024-01-01
  • 用yum安装MySQLdb模块的步骤方法

    用yum安装MySQLdb模块的步骤方法

    在python2.7版本中,MySQLdb模块还不是python的内置模块,但是MySQLdb模块又是Python与MySQL连接的桥梁,对于作为MySQL DBA又很喜欢Python语言的我来说,MySQLdb真的是必需品呢。所以就需要自己进行安装了,这篇文章就给大家详细介绍了关于用yum安装MySQLdb模块的步骤。
    2016-12-12
  • Python如何将两个三维模型(obj)合成一个三维模型(obj)

    Python如何将两个三维模型(obj)合成一个三维模型(obj)

    这篇文章主要介绍了Python如何将两个三维模型(obj)合成一个三维模型(obj)问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • Linux环境下GPU版本的pytorch安装

    Linux环境下GPU版本的pytorch安装

    使用默认的源地址下载速度很慢,所以一般都是使用国内源,今天花了点时间配置安装,所以记录一下,需要的朋友们下面随着小编来一起学习学习吧
    2021-05-05
  • python定时器(Timer)用法简单实例

    python定时器(Timer)用法简单实例

    这篇文章主要介绍了python定时器(Timer)用法,以一个简单实例形式分析了定时器(Timer)实现延迟调用的技巧,需要的朋友可以参考下
    2015-06-06
  • 一种Python工具的License授权机制详解

    一种Python工具的License授权机制详解

    这篇文章主要介绍了一种Python工具的License授权机制,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • Python json模块dumps、loads操作示例

    Python json模块dumps、loads操作示例

    这篇文章主要介绍了Python json模块dumps、loads操作,结合实例形式分析了Python使用json模块针对json数据的载入、读取、打印、编码转换等相关操作技巧,需要的朋友可以参考下
    2018-09-09
  • pytorch加载语音类自定义数据集的方法教程

    pytorch加载语音类自定义数据集的方法教程

    这篇文章主要给大家介绍了关于pytorch加载语音类自定义数据集的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Django uwsgi Nginx 的生产环境部署详解

    Django uwsgi Nginx 的生产环境部署详解

    这篇文章主要介绍了Django uwsgi Nginx 的生产环境部署详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-02-02
  • Python数据分析库PyGWalker的强大交互式功能界面探索

    Python数据分析库PyGWalker的强大交互式功能界面探索

    这篇文章主要介绍了Python数据分析库PyGWalker的强大交互式功能界面探索有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2024-01-01

最新评论