![ba56e6197a0290a4001c930300d9136b.png](https://img-blog.csdnimg.cn/img_convert/ba56e6197a0290a4001c930300d9136b.png)
一、概述
链表也是比较常见的数据结构,其与数组经常做对比,对于数组,需要连续的内存地址来存储数据,对内存的要求较高,而链表恰恰相反,它并不需要一块连续的内存空间,它通过“指针”将一组零散的内存块串联起来使用。
![0c8be9e25a130b7ae244036bf65fd150.png](https://img-blog.csdnimg.cn/img_convert/0c8be9e25a130b7ae244036bf65fd150.png)
先介绍三种最常见的链表结构,它们分别是:单链表、双向链表和循环链表。
二、常见链表结构
常见的链表结构,它们分别是:单链表、双向链表和循环链表。
单链表
单链表比较简单,通过指针将一组零散的内存块串联在一起。其中,我们把内存块称为链表的“结点”。为了将所有的结点串起来,每个链表的结点除了存储数据之外,还需要记录链上的下一个结点的地址。
![3ee6883e80990bcdfa9ce73b9991e873.png](https://img-blog.csdnimg.cn/img_convert/3ee6883e80990bcdfa9ce73b9991e873.png)
代码实现:
"""
循环链表
循环链表是一种特殊的单链表。它跟单链表唯一的区别就在尾结点,其中:单链表的尾结点指针指向空地址,表示这就是最后的结点了,而循环链表的尾结点指针是指向链表的头结点。
![0ca07e1382899a5cd2a6dd5c78566735.png](https://img-blog.csdnimg.cn/img_convert/0ca07e1382899a5cd2a6dd5c78566735.png)
代码实现:
"""
* @Author: Jack Shan
* @Date: 2020-09-27 13:50:06
* @Last Modified by: Jack Shan
* @Last Modified time: 2020-09-27 13:50:06
"""
# 定义节点
class Node():
# 初始化
def __init__(self, value):
self.value = value
self.next = None
# 定义链表(单向链表)
class CircleLinkList():
# 初始化
def __init__(self):
self._head = None
# 判断链表是否为空
def is_empty(self):
return self._head is None
# 链表长度
def length(self):
if self.is_empty():
return 0
count = 1
current = self._head
while current.next != self._head:
count += 1
current = current.next
return count
# 遍历链表
def items(self):
current = self._head
while current.next != self._head:
yield current.value
current = current.next
yield current.value
# 向链表头部添加元素
def insert_head(self, value):
new_node = Node(value)
if self._head is not None:
new_node.next = self._head
current = self._head
while current.next != self._head:
current = current.next
current.next = new_node
else:
self._head = new_node
new_node.next = self._head
self._head = new_node
# 尾部添加元素
def append(self, value):
new_node = Node(value)
if self._head is not None:
current = self._head
while current.next != self._head:
current = current.next
current.next = new_node
new_node.next = self._head
else:
self._head = new_node
new_node.next = self._head
# 指定位置插入元素
def insert(self, index, value):
if index <= 0: # 指定位置小于等于0,头部添加
self.insert_head(value)
elif index > self.length()-1:
self.append(value)
else:
new_node = Node(value)
current = self._head
for _ in range(index-1):
current = current.next
new_node.next = current.next
current.next = new_node
# 删除节点
def remove(self, value):
# 若链表为空
if self.is_empty():
return
current = self._head
pre = Node
# 如果第一个元素为需要删除的元素
if current.value == value:
# 如果链表不止一个元素
if current.next != self._head:
while current.next != self._head:
current = current.next
current.next = self._head.next
self._head = self._head.next
# 如果只有一个元素
else:
self._head = None
# 如果删除的是链表中间的元素
else:
pre = self._head
while current.next != self._head:
if current.value == value:
pre.next = current.next
return True
else:
pre = current
current = current.next
# 如果删除的为结尾的元素
if current.value == value:
pre.next = self._head
return True
# 查找元素是否存在
def find(self, value):
return value in self.items()
if __name__ == "__main__":
circle_link = CircleLinkList()
print(circle_link.is_empty())
print(circle_link.length())
circle_link.insert_head(10)
print(circle_link.is_empty())
circle_link.insert_head(20)
circle_link.insert_head(1)
circle_link.insert_head(0)
print(list(circle_link.items()))
for i in range(2, 9):
circle_link.append(i)
print(list(circle_link.items()))
print(circle_link.find(10))
circle_link.insert(5, 30)
print(list(circle_link.items()))
circle_link.remove(30)
print(list(circle_link.items()))
circle_link.remove(0)
print(list(circle_link.items()))
circle_link.remove(8)
print(list(circle_link.items()))
circle_link.remove(80)
print(list(circle_link.items()))
双向链表
单向链表只有一个方向,结点只有一个后继指针 next 指向后面的结点。而双向链表,顾名思义,它支持两个方向,每个结点不止有一个后继指针 next 指向后面的结点,还有一个前驱指针 prev 指向前面的结点。
![c06cc4e6d8079dccec70b482b3d8101c.png](https://img-blog.csdnimg.cn/img_convert/c06cc4e6d8079dccec70b482b3d8101c.png)
代码实现:
"""
* @Author: Jack Shan
* @Date: 2020-09-27 14:44:13
* @Last Modified by: Jack Shan
* @Last Modified time: 2020-09-27 14:44:13
"""
# 定义节点
class Node():
# 初始化
def __init__(self, value):
self.value = value
self.next = None
self.pre = None
# 定义链表(单向链表)
class BilateralLinkList():
# 初始化
def __init__(self):
self._head = None
# 判断链表是否为空
def is_empty(self):
return self._head is None
# 链表长度
def length(self):
count = 0
current = self._head
while current is not None:
count = count + 1
current = current.next
return count
# 遍历链表
def items(self):
current = self._head
while current is not None:
yield current.value
current = current.next
# 向链表头部添加元素
def insert_head(self, value):
new_node = Node(value)
# 链表为空时
if self._head is None:
# 头部结点指针修改为新结点
self._head = new_node
else:
# 新节点指向原来的头部节点
new_node.next = self._head
# 原来头部节点pre指向新节点
self._head.pre = new_node
# head指向新节点
self._head = new_node
# 尾部添加元素
def append(self, value):
new_node = Node(value)
if self._head is None:
# 头部结点指针修改为新结点
self._head = new_node
else:
current = self._head
while current.next is not None:
current = current.next
current.next = new_node
new_node.pre = current
# 指定位置插入元素
def insert(self, index, value):
if index <= 0: # 指定位置小于等于0,头部添加
self.insert_head(value)
elif index > self.length()-1:
self.append(value)
else:
current = self._head
new_node = Node(value)
for _ in range(index-1):
current = current.next
# 新节点的前一个节点指向当前节点的上一个节点
new_node.pre = current.pre
# 新节点的下一个节点指向当前节点
new_node.next = current
# 当前节点的上一个节点指向新节点
current.pre.next = new_node
# 当前结点的向上指针指向新结点
current.pre = new_node
# 删除节点
def remove(self, value):
if self.is_empty():
return
current = self._head
# 删除的元素为第一个元素
if current.value == value:
# 链表中只有一个元素
if current.next is None:
self._head = None
return True
else:
self._head = current.next
current.next.pre = None
return True
while current.next is not None:
if current.value == value:
current.pre.next = current.next
current.next.pre = current.pre
return True
current = current.next
# 删除元素在最后一个
if current.value == value:
current.pre.next = None
return True
# 查找元素是否存在
def find(self, value):
return value in self.items()
if __name__ == "__main__":
link_list = BilateralLinkList()
print(link_list.is_empty())
print(link_list.length())
link_list.insert_head(10)
print(link_list.is_empty())
link_list.insert_head(20)
link_list.insert_head(1)
link_list.insert_head(0)
print(list(link_list.items()))
for i in range(2, 9):
link_list.append(i)
print(list(link_list.items()))
print(link_list.find(10))
link_list.remove(0)
print(list(link_list.items()))
link_list.remove(3)
print(list(link_list.items()))
link_list.remove(8)
print(list(link_list.items()))
三、链表代码编写技巧
理解指针和引用的含义
对于指针的理解,可以记住下面的这句话:
将某个变量赋值给指针,实际上就是将这个变量的地址赋值给指针,或者反过来说,指针中存储了这个变量的内存地址,指向了这个变量,通过指针就能找到这个变量。
python中使用的引用,其理解可以参考:python中的引用
警惕指针丢失和内存泄漏
举个例子,当我们想在链表中插入数据时,如下图所示:
![7d29837aa6ec52e49eadd26565b3607a.png](https://img-blog.csdnimg.cn/img_convert/7d29837aa6ec52e49eadd26565b3607a.png)
将x插入a和b之间,如果我们使用如下代码:
p
上述代码中,第一行代码中p指向x,如果执行第二行代码,则x指向x的自身,这样就会导致内存泄漏,因此我们在编写代码时候应该注意前后顺序,将1、2两行代码交换即可。
重点留意边界条件处理
主要是针对链表为空、链表中只有一个节点、链表中只有两个节点以及在处理头部节点和尾部节点的方式,写别的代码时候类似,需要处理边界情况或者异常的情况。
举例画图,辅助思考
对于稍微复杂的链表操作,比如前面我们提到的单链表反转,指针一会儿指这,一会儿指那,一会儿就被绕晕了。总感觉脑容量不够,想不清楚。所以这个时候就要使用大招了,举例法和画图法。
四、链表案例
主要是leetcode上的常考案例题,包括单链表反转、链表中环的检测、两个有序的链表合并、删除链表倒数第 n 个结点、求链表的中间结点。
单链表反转