单链表的节点,包含值域data与指针next,所以其定义也很简单:
class Node:
def __init__(self, data):
self.data = data
self.next = None
单链表,包含了头节点head,链表长度size,方法包括了增加add, 删除delete, 插入insert, 打印遍历链表print_link等等,可以根据自己的需要,来写相应的方法,这里只写了几个。
对单链表的操作,最主要的就是对其指针的操作,经常要引入临时变量来存储指针指向的值或者节点。
代码
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def add(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
self.size += 1
return
p = self.head
while p.next:
p = p.next
p.next = new_node
self.size += 1
def delete(self):
if self.head is None:
print("The link is None")
return
elif self.head.next is None:
self.head = None
self.size -= 1
else:
cur = self.head
pre = cur
while cur.next:
pre = cur
cur = cur.next
pre.next = None
self.size -= 1
def insert(self, target, value):
new_node = Node(value)
if self.head is None:
print("The link is None")
return
cur = self.head
while cur.data != target and cur.next:
cur = cur.next
if cur.data == target and cur.next:
new_node.next = cur.next
cur.next = new_node
self.size += 1
elif cur.data == target and cur.next is None:
cur.next = new_node
self.size += 1
else:
print("Cannot find ", target)
return
def print_link(self):
if self.head is None:
print("The link is None")
return
cur = self.head
while cur:
print(cur.data)
cur = cur.next