二、链表
1. 链表的定义
- 为什么需要链表?
顺序表的构建需要预先知道数据大小来申请连续的存储空间,而在进行扩充时又需要进行数据的搬迁,所以使用起来并不是很灵活。链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。
- 链表的定义
链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是不像顺序表一样连续存储数据,而是在每一个节点(数据存储单元)里存放下一个节点的位置信息(即地址)。
2. 单向链表
- 单向链表也叫单链表,是链表中最简单的一种形式,它的每个节点包含两个域,一个信息域(元素域) 和一个链接域。这个链接指向链表中的下一个节点,而最后一个节点的链接域则指向一个空值。
- 结构
元素域elem用来存放具体的数据。
链接域next用来存放下一个节点的位置(python中的标识)
变量p指向链表的头节点(首节点)的位置,从p出发能找到表中的任意节点。
2.1 节点实现
class Node(object):
def __init__(self, elem):
self.elem = elem
self.next = None
2.2 链表实现
- 单链表可执行的操作
is_empty() 链表是否为空
length() 链表长度
travel() 遍历整个链表
add(item) 链表头部添加节点
append(item) 链表尾部添加节点
insert(pos, item) 指定位置添加节点
remove(item) 删除节点
search(item) 查找节点是否存在
- 代码实现(代码后方有几种情况的图示解释)
class SingleLinkList(object):
def __init__(self, node=None):
self.__head = node
def is_empty(self):
"""链表是否为空"""
return self.__head is None
def length(self):
"""链表长度"""
cursor = self.__head
count = 0
while cursor is not None:
count += 1
cursor = cursor.next
return count
def travel(self):
"""遍历整个链表"""
cursor = self.__head
while cursor is not None:
print(cursor.elem, end='\t')
cursor = cursor.next
print("")
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:
cursor = self.__head
while cursor.next is not None:
cursor = cursor.next
cursor.next = node
def insert(self, pos, item):
"""指定位置添加元素
:param pos 从0开始
"""
if pos <= 0:
self.add(item)
elif pos > self.length()-1:
self.append(item)
else:
node = Node(item)
prior = self.__head
count = 0
while count < pos-1:
prior = prior.next
count += 1
node.next = prior.next
prior.next = node
def remove(self, item):
"""删除节点"""
cursor = self.__head
prior = None
while cursor is not None:
if cursor.elem == item:
if cursor == self.__head:
self.__head = cursor.next
else:
prior.next = cursor.next
return True
else:
prior = cursor
cursor = cursor.next
def search(self, item):
"""查找节点是否存在"""
cursor = self.__head
while cursor is not None:
if cursor.elem == item:
return True
else:
cursor = cursor.next
return False
- 头部添加节点
- 指定位置添加节点
- 删除节点