一、认识单链表
1. 链表元素(结点)
链表元素包含有 元素值 和 指向下一个元素的指针
# 链表元素的定义
class Node:
def __init__(self, elem):
self.elem = elem
self.next = None
2. 单链表
由一个个链表元素构成,最后一个元素的next指向 None
class SingleLinkList:
"""单链表"""
def __init__(self, head=None):
self.__head = head
二、单链表的基本操作
基本操作:创建+增删改查
1. 列表创建
from node import Node
from single_link_list import SingleLinkList
if __name__ == '__main__':
head = Node(1)
node2 = Node(2)
node3 = Node(3)
head.next = node2
node2.next = node3
sll = SingleLinkList(head)
2. 增加
增加至头部 | 增加至尾部 | 增加至中间
from node import Node
class SingleLinkList:
def __init__(self, head):
self.__head = head
def add(self, item):
# 增加元素至头部
node = Node(item)
node.next = self.__head
self.__head = node
def append(self, item):
# 增加元素至尾部,注意链表为空的情况
node = Node(item)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next:
cur = cur.next
cur.next = node
def is_empty(self):
return self.__head is None
def insert(self, pos, item):
# 添加链表至中间,链表插入
"""
link_list: 0 1 2 3 4 5 position 1~6 new_load.val=x
1. 在链表的头部插入 position=1 => x 0 1 2 3 4 5
2. 在链表的中间插入 position=4 插入2-3之间 => 0 1 2 x 3 4 5
3. 在链表的尾部插入 position=7 => 0 1 2 3 4 5 x
4. 超出范围,不合法 position<1 or position>7
"""
length = self.length()
if pos < 1 or pos > length + 1:
raise ValueError(f"position {pos} is out of range")
elif pos == 1:
self.add(item)
elif pos == length + 1:
self.append(item)
else:
node = Node(item)
index = 1
cur = self.__head
while index < pos - 1:
index += 1
cur = cur.next
node.next = cur.next
cur.next = node
def length(self):
"""链表长度"""
cur = self.__head
count = 0
while cur:
count += 1
cur = cur.next
return count
3. 删除
注意特殊情况:链表为空,删除首元素
def remove_item(self, item):
"""删除节点"""
cur = self.__head
pre = None
while cur:
if cur.item == item:
# 如果第一个就是删除的节点
if not pre:
self.__head = cur.next
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
def remove_pos(self, pos):
"""
删除节点(位置)
link_list: 0 1 2 3 4 5 position 1~6
1. 删除链表头部 position=1 => 1 2 3 4 5
2. 删除链表中间 position=4 => 0 1 2 4 5
3. 删除链表尾部 position=6 => 0 1 2 3 4
4. 超出范围,不合法 position<1 or position>6
"""
if self.is_empty():
return
length = self.length()
if pos < 1 or pos > length:
raise ValueError(f"position {pos} is out of range")
if pos == 1:
self.__head = self.__head.next
pre_node = self.__head
index = 1
while index < pos - 1:
index += 1
pre_node = pre_node.next
cur_node = pre_node.next
pre_node.next = cur_node.next
4. 修改
修改节点值,替换节点
5. 查询
获取链表长度,查找元素