Python编程实现双链表,栈,队列及二叉树的方法示例
作者:王辉_Python 发布时间:2021-11-10 12:35:17
标签: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程序设计有所帮助。
来源:http://www.cnblogs.com/PrettyTom/p/6677993.html


猜你喜欢
- 摘要:本篇博客介绍了本教程的目标、适用人群、YOLOv5简介和车牌识别的意义和应用场景。为后续章节打下基础,帮助读者了解YOLOv5和车牌识
- 字段是Python是字典中唯一的键-值类型,是Python中非常重要的数据结构,因其用哈希的方式存储数据,其复杂度为O(1),速度非常快。下
- 做机器学习的一定对支持向量机(support vecto
- 本文实例讲述了python实现写日志封装类。分享给大家供大家参考。具体如下:# encoding:utf-8import sysimport
- 前言前几天下载安装了最新版的MySQL 8.0.22,遇到了不少问题,参考了一些方法,最终得以解决。今天将自己的安装过程记录下来,希望对各位
- MaxDB和MySQL是独立的数据库管理服务器。系统间的协同性是可能的,通过相应的方式,系统能够彼此交换数据。要想在MaxDB和MySQL之
- 微信,一个日活10亿的超级app,不仅在国内社交独领风骚,在国外社交也同样占有一席之地,今天我们要将便是如何用Python来生成一个微信机器
- 前言有多种 Python 模块用于隐藏用户输入的密码,其中一个是**maskpass()模块。在 Python 中,借助maskpass()
- 问题引入什么时候选择 T 作为参数类型,什么时候选择 *T 作为参数类型?[ ] T 是传递的指针还是值?选择 [ ] T 还是 [ ] *
- 快速掌握 Mysql数据库对文件操作的封装在查看Mysql对文件的操作中,它在不同的操作系统上对文件的操作,除了使用标准C运行库函数,包括o
- 上一篇文章为大家介绍了 GoFrame gcache使用实践 | 缓存控制 淘汰策略 ,得到了大家积极的反馈。后续几篇文章再接再厉,仍然为大
- 默认vue项目中已经使用vue-cli生成,安装axios,基于element-ui开发,axiosconfig目录和api目录是同级,主要
- 前言GraphQL是一种新的API设计语言,它提供了更加灵活、高效的API查询方式。与RESTful API相比,GraphQL可以更好地满
- 手痒痒系列之简单的放大镜写了个放大镜功能,可以设置显示的宽高width,height显示的位置,float ‘left’ 'righ
- 如下所示:a = [0, 1, 2, 3, 4, 0, 2, 3, 6, 7, 5]selected = [x for x in a if
- 什么是结构体Go语言中没有“类”的概念,也不支持“类”的继承
- 前言索引和切片是NumPy中最重要最常用的操作。熟练使用NumPy切片操作是数据处理和机器学习的前提,所以一定要掌握好。参考NumPy官方文
- 文章背景:某天,我的一个同事给我看了CSDN上面的一篇关于编程语言排行榜的文章,里面我看到VB还是排名很不错的,我就说,asp(vbscri
- 本文实例讲述了php7 参数、整形及字符串处理机制修改。分享给大家供大家参考,具体如下:参数处理机制修改一、重复参数命名不再支持。重复的参数
- 姓名的翻译: 英语是名(First name)在前,姓(Last name)在后。中文地址的翻译:如果你英语水平不高,填表时只要国家名用英语