链表是一个没有顺序但是一个有一个前后相对位置的数据结构
下面是链表的实现及其相对方法
# 链表是由基本元素节点构成的
# 每个节点需要保存两个信息,一个是本身所携带的值,另一个是下一个指向的值
class Node:
def __init__(self,val):
self.val = val
self.next = None
# 定义链表
class LinkedList:
def __init__(self,head):
self.head = head
self.count = 0
# 定义链表的展示方法 返回的是一个列表
def show(self):
linkedlist = []
current = self.head
while current:
linkedlist.append(current.val)
current = current.next
return linkedlist
# 定义链表的长度,返回的是一个int类型的整数
def size(self):
current = self.head
while current:
self.count += 1
current = current.next
return self.count
# 定义链表的添加方法,这个方法在链表的首段添加
def addAtHead(self,val):
node = Node(val) # 产生当前元素对应的节点
node.next = self.head
self.head = node
# 定义链表的添加方法,在链表的最后位置添加
def addAtTail(self,val): # 添加到末尾
node = Node(val)
current = self.head
while current.next is not None:
current = current.next
current.next = node
# 定义链表的添加方法,需要传入索引和值,将会在输入的索引index前加入该值
def addAtIndex(self,index,val):
if index == 0:
self.addAtHead(val)
node = Node(val)
current = self.head
previous = None
for i in range(index-1):
current = current.next
node.next = current.next
current.next = node
if index > self.count -1:
return
# 定义链表的删除方法,该方法需要传输索引,删除这个索引对应的值
def deleteAtIndex(self,index):
if index == 0:
current = self.head.next
self.head = current
else:
current = self.head
previous = None
for i in range(index):
previous = current
current = current.next
previous.next = current.next
# 定义链表的删除方法,该方法需要传入值val,将会删除所有与传入值val相同的节点
def deleteAtVal(self,val):
if self.head.val == val:
self.deleteAtIndex(0)
else:
current = self.head
previous = None
while current and current.next != None:
previous = current
current = current.next
if current.val == val:
previous.next = current.next
# 获取传入索引的节点对象,可调用节点的属性来查询相关内容
def getNode(self,index): # 返回节点对象 , 需要调用属性来查询值和下一个值
current = self.head
for i in range(index-1):
current = current.next
return current
# 判断链表是否为空,为空返回True
def isEmpty(self):
bool = self.show()
return bool == []
if __name__ == '__main__':
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node1.next = node2
node2.next = node3
l = LinkedList(head = node1) # [1,2,3]
l.addAtIndex(index = 0,val = 0) # [0,1,2,3]
l.addAtTail(4) # [0,1,2,3,4]
l.addAtTail(3) # [0,1,2,3,4,3]
l.deleteAtVal(0) # [1,2,3,4,3]
print(l.getNode(0).val) # 1
print(l.show()) # [1,2,3,4,3]
print(l.size()) # 5
有些方法在main中没有进行调用,可以自行尝试,应该是没有什么问题的