节点类的实现
class Node:
def __init__(self,value,next=None):
self.value = value
self.next=next
链表类的实现
class Link:
def __init__(self):
self.pHead = Node(-1)
def get_length(self):
length = 0
temp = self.pHead.next
while temp != None:
length += 1
temp = temp.next
return length
def is_empty(self):
empty = True
if self.get_length() != 0:
empty = False
return empty
def insert_node(self, k: int, value):
length = self.get_length()
if k < 1 or k > (length + 1):
raise ValueError("the value of k is out range of link")
node = Node(value)
pre = self.pHead
for i in range(1, k):
pre = pre.next
if k == 1:
temp = self.pHead.next
self.pHead.next = node
node.next = temp
elif k > 1:
temp = pre.next
pre.next = node
node.next = temp
def delete_node(self, value):
locate = self.pHead
while locate.next != None:
if locate.next.value == value:
temp = locate.next
temp = temp.next
locate.next = temp
break
locate = locate.next
def reserve_link(self):
temp = self.pHead.next
post = None
while temp != None:
pre = post
post = temp
temp = temp.next
post.next = pre
self.pHead.next = post
def browser(self):
temp = self.pHead.next
while temp != None:
print(temp.value, end="")
temp = temp.next
if temp != None:
print(" -> ", end="")
print()
测试程序
def test():
link = Link()
print("长度:",link.get_length())
print("是否为空:",link.is_empty())
link.insert_node(1,15)
link.insert_node(1,20)
link.insert_node(2,30)
link.insert_node(4,-5)
link.insert_node(4,144)
link.insert_node(6,88)
link.browser()
link.delete_node(88)
link.browser()
print("长度:", link.get_length())
print("是否为空:", link.is_empty())
test()