前言
我们在日常开发中,可能语言本身的数据结构难以满足开发。这里简单的来实现一些经典的数据结构。
队列
我们可以使用list轻松的实现队列
queue1 = []
queue1.insert(0, 'a')
queue1.insert(0, 'b')
queue1.insert(0, 'c')
print(queue1)
['c', 'b', 'a']
queue1.pop()
a
queue1.pop()
b
然而,这是低效的,因为当您向开始添加新元素时,列表必须按一个索引移动所有元素。
通常最好的做法是使用Python的collections模块中的deque类。deque对追加和弹出操作进行了优化。
queue2 = deque()
queue2.append('a')
queue2.append('b')
queue2.append('c')
print(queue2)
deque(['a', 'b', 'c'])
queue2.popleft()
a
queue2.popleft()
b
栈
同样的,我们可以使用list轻松实现队列。
stack1 = []
stack1.append("a")
stack1.append("b")
stack1.append("c")
print(stack1)
['a', 'b', 'c']
stack1.pop()
c
stack1.pop()
b
在这里list
对象可以实现自动缩放和对象清理,所以这里建议使用此方式。当然也可以通过deque来实现。
from collections import deque
stack2 = deque()
stack2.append("a")
stack2.append("b")
stack2.append("c")
stack2.pop()
stack2.pop()
stack2.pop()
c
b
a
链表
链表实现的相对较为复杂
#先定一个node的类
class Node(): #value + next
def __init__ (self, value = None, next = None):
self._value = value
self._next = next
def getValue(self):
return self._value
def getNext(self):
return self._next
def setValue(self,new_value):
self._value = new_value
def setNext(self, new_next):
self._next = new_next
#实现Linked List及其各类操作方法
class LinkedList():
def __init__(self): #初始化链表为空表
self._head = Node()
self._tail = None
self._length = 0
#检测是否为空
def isEmpty(self):
return self._head == None
#add在链表前端添加元素:O(1)
def add(self,value):
newnode = Node(value, None) #create一个node(为了插进一个链表)
newnode.setNext(self._head)
self._head = newnode
#append在链表尾部添加元素:O(n)
def append(self, value):
newnode = Node(value)
if self.isEmpty():
self._head = newnode #若为空表,将添加的元素设为第一个元素
else:
current = self._head
while current.getNext() != None:
current = current.getNext() #遍历链表
current.setNext(newnode) #此时current为链表最后的元素
#search检索元素是否在链表中
def search(self,value):
current=self._head
foundvalue = False
while current != None and not foundvalue:
if current.getValue() == value:
foundvalue = True
else:
current=current.getNext()
return foundvalue
#index索引元素在链表中的位置
def index(self, value):
current = self._head
count = 0
found = None
while current != None and not found:
count += 1
if current.getValue()==value:
found = True
else:
current=current.getNext()
if found:
return count
else:
raise ValueError ('%s is not in linkedlist'%value)
#remove删除链表中的某项元素
def remove(self, value):
current = self._head
pre = None
while current!=None:
if current.getValue() == value:
if not pre:
self._head = current.getNext()
else:
pre.setNext(current.getNext())
break
else:
pre = current
current = current.getNext()
#insert链表中插入元素
def insert(self, pos, value):
if pos <= 1:
self.add(value)
elif pos > self.size():
self.append(value)
else:
temp = Node(value)
count = 1
pre = None
current = self._head
while count < pos:
count += 1
pre = current
current = current.getNext()
pre.setNext(temp)
temp.setNext(current)
树结构
树结构同样是软件开发过程中一种常见的数据结构。
from graphviz import Digraph
import uuid
from random import sample
# 二叉树
class Tree:
def __init__(self, data=None, left=None, right=None):
self.data = data # 数据域
self.left = left # 左子树
self.right = right # 右子树
self.dot = Digraph(comment='Binary Tree')
# 前序遍历
def preorder(self):
if self.data is not None:
print(self.data, end=' ')
if self.left is not None:
self.left.preorder()
if self.right is not None:
self.right.preorder()
# 中序遍历
def inorder(self):
if self.left is not None:
self.left.inorder()
if self.data is not None:
print(self.data, end=' ')
if self.right is not None:
self.right.inorder()
# 后序遍历
def postorder(self):
if self.left is not None:
self.left.postorder()
if self.right is not None:
self.right.postorder()
if self.data is not None:
print(self.data, end=' ')
# 层序遍历
def levelorder(self):
# 返回某个节点的左孩子
def LChild_Of_Node(node):
return node.left if node.left is not None else None
# 返回某个节点的右孩子
def RChild_Of_Node(node):
return node.right if node.right is not None else None
# 层序遍历列表
level_order = []
# 是否添加根节点中的数据
if self.data is not None:
level_order.append([self])
# 二叉树的高度
height = self.height()
if height >= 1:
# 对第二层及其以后的层数进行操作, 在level_order中添加节点而不是数据
for _ in range(2, height + 1):
level = [] # 该层的节点
for node in level_order[-1]:
# 如果左孩子非空,则添加左孩子
if LChild_Of_Node(node):
level.append(LChild_Of_Node(node))
# 如果右孩子非空,则添加右孩子
if RChild_Of_Node(node):
level.append(RChild_Of_Node(node))
# 如果该层非空,则添加该层
if level:
level_order.append(level)
# 取出每层中的数据
for i in range(0, height): # 层数
for index in range(len(level_order[i])):
level_order[i][index] = level_order[i][index].data
return level_order
# 高度
def height(self):
# 空的树高度为0, 只有root节点的树高度为1
if self.data is None:
return 0
elif self.left is None and self.right is None:
return 1
elif self.left is None and self.right is not None:
return 1 + self.right.height()
elif self.left is not None and self.right is None:
return 1 + self.left.height()
else:
return 1 + max(self.left.height(), self.right.height())
# 叶子节点
def leaves(self):
if self.data is None:
return None
elif self.left is None and self.right is None:
print(self.data, end=' ')
elif self.left is None and self.right is not None:
self.right.leaves()
elif self.right is None and self.left is not None:
self.left.leaves()
else:
self.left.leaves()
self.right.leaves()