一、单链表
单向链表的存储结构比较简单,在存储上,它能够用一组任意的存储单元存储线性表的数据元素(这组存储单元可以是连续的,也可以是不连续的)。每个元素包含两个域,其中存储数据元素信息的域称为数据域;存储直接后继存储位置的域称为指针域。指针域中存储的信息称作指针或链。
二、双向链表
双向链表的存储结构相对于单向链表更加复杂。在双向链表中,每个节点中有两个指针域,一个指向直接后继,另一个指向直接前驱,当连接为最后一个连接时,指向空值或者空列表
三、循环链表
循环链表是另一种形式的链式存储结构。其特点是表中最后一个节点的指针域指向头节点,整个链表形成一个环。由此,从表中任意节点出发均可找到表中其他节点
四、单链表实现
# 链节点
class ListNode:
def __init__(self, val=0, next=None):
self.val = val # 表示数据元素的值
self.next = next # 表示后继指针
# 链表
class LinkedList:
def __init__(self):
self.head = None # 表示链表头节点
# 动态生成链节点,并且依次将其连接到链表中
def create(self, data):
self.head = ListNode(0)
cur = self.head
for i in range(len(data)):
node = ListNode(data[i])
cur.next = node
cur = cur.next
# 求链表长度
def getLen(self):
count = 0
cur = self.head
while cur:
count += 1
cur = cur.next
return count
# 查找元素
def searchVal(self, val):
cur = self.head
while cur:
if cur.next.val == val:
return cur
cur = cur.next
return None
# 头插法
def insertByHead(self, val):
node = ListNode(val)
node.next = self.head
self.head = node
# 尾插法
def insertByEnd(self, val):
node = ListNode(val)
cur = self.head
while cur.next:
cur = cur.next
cur.next = node
# 中间插入
def insertByMiddle(self, index, val):
count = 0
cur = self.head
while cur and count < index - 1:
count += 1
cur = cur.next
node = ListNode(val)
node.next = cur.next
cur.next = node
# 修改元素
def update(self, index, val):
cur = self.head
count = 0
while cur and count < index - 1:
count += 1
cur = cur.next
cur.val = val
# 头删法
def deleteByHead(self):
self.head = self.head.next
# 尾删法
def deleteByEnd(self):
cur = self.head
while cur.next:
cur = cur.next
self.cur = None
# 中间删除
def deleteByMiddle(self, index):
count = 0
cur = self.head
while cur and count < index - 1:
count += 1
cur = cur.next
cur.next = cur.next.next