# 链表(离散)修正列表(连续)的弊端
class Node():
def __init__(self, item):
# 指向一个对象
self.item = item
# 对象的下一个为空
self.next = None
class Link():
def __init__(self):
# 头节点
self.head = None
# 添加对象(头插法)
def addHead(self, item):
# 添加对象
node = Node(item)
# 头指针指向对象
node.next = self.head
self.head = node
# 遍历
def travel(self):
# print(self.head.item)
cur = self.head
while cur != None:
print(cur.item)
cur = cur.next
# 判断链表是否为空
def isEmpty(self):
return self.head == Node
# 链表的长度
def length(self):
# 计数
cnt = 0
cur = self.head
while cur != None:
cnt += 1
cur = cur.next
return cnt
# 链表尾部添加对象(尾插法)
def append(self, item):
node = Node(item)
# 判断链表是否为空
if self.isEmpty():
self.head = node
return
else:
# 链表非空
cur = self.head
# pre 指向cur前面的一个对象
pre = None
# 找到最后一个对象
while cur != None:
pre = cur
cur = cur.next
# 添加对象
pre.next = node
# 插入对象
def insertNode(self, item, pos):
node = Node(item)
# 非空
pre = None
cur = self.head
if pos == 0:
self.addHead(item)
return
for i in range(pos):
pre = cur
cur = cur.next
pre.next = node
node.next = cur
# 删除对象
def removeNode(self, item):
self.item = item
pre = None
cur = self.head
# 头节点(第一个对象)单独处理
if self.head.item == item:
self.head = cur.next
return
while cur != None:
if cur.item == self.item:
# 存在对象之后,进行删除
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
link = Link()
link.addHead(1)
link.addHead(2)
link.addHead(3)
link.addHead(4)
link.addHead(5)
# link.travel()
# print(link.isEmpty())
# print(link.length())
# link.append(99)
# link.travel()
# print(link.length())
# link.insertNode(88, 3)
# link.travel()
link.removeNode(5)
link.travel()
Python单链表头插法(包含尾插法)的基础操作
于 2023-11-07 17:20:44 首次发布