首先简单介绍单链表:
单链表结构
节点包含:信息域(元素域)、链接域
元素域:存放具体数据
链接域:存放下一个节点的位置(标识)
从头节点位置可以找到表中任意节点
上代码:
'''创建节点类和链表类'''
# 定义单链表节点
class Node(object):
def __init__(self, item):
# item存放数据的元素
self.item = item
# next下一个节点标识(链接),初始化None
self.next = None
class SingleLinkList(object):
'''单链表类'''
def __init__(self):
# 初始化头结点,头结点为私有属性
self.__head = None
def is_empty(self):
# 判断头结点是否为空
return self.__head is None
def length(self):
'''链表长度'''
# 定义count记录节点个数
count = 0
# cur初始状态指向头节点
cur = self.__head
# 尾节点之后为None,判断:
while cur is not None:
count += 1
cur = cur.next
return count
def travel(self):
'''遍历链表'''
# 定义游标变量,从头往后移动根据尾节点指向None判断:
cur = self.__head
# 判断当前节点为None
while cur is not None:
# 输出当前节点
print(cur.item, end=' ')
# 使游标指向下一个节点
cur = cur.next
print()
def add(self, item):
'''向链表头部添加元素'''
# 创建新节点
node = Node(item)
# 1.先让新节点指向老的头结点,不能让head直接指向新节点,不然原由数据会丢失
node.next = self.__head
# 2.再让head指向新节点
self.__head = node
def append(self, item):
'''向链表尾部添加元素'''
# 考虑链表为空的情况
if self.is_empty():
self.add(item)
return
# 1.遍历找到尾节点
cur = self.__head
# 判断尾节点指向为None
while cur.next is not None:
# 尾节点指向None,不进入循环
cur = cur.next
# 创建新节点
node = Node(item)
# 尾节点指向新节点
cur.next = node
def insert(self, pos, item):
'''向指定位置添加元素'''
# 健壮性,处理额外情况
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
'''超出下标的情况'''
self.append(item)
else:
'''正常情况'''
# 单链接要在指定位置的前边一个位置才能往后操作
# 获取指定位置前一个节点
# 定义index记录当前游标的下标
cur = self.__head
index = 0
while index < (pos - 1):
# 游标指向下一个节点
cur = cur.next
index += 1
# while结束后,cur指向pos的前一个节点
# 创建新节点
node = Node(item)
# 新节点的链接域指向下一个节点(当前节点的链接域)
node.next = cur.next
# 当前cur的链接域指向新节点信息域
cur.next = node
def remove(self,item):
'''删除节点'''
cur = self.__head
# 定义pre为cur前一个节点
pre = None
while cur is not None:
# 判断要删除的节点
if cur.item == item:
if pre is None:
# 说名删除的cur是头结点
self.__head = cur.next
else:
pre.next = cur.next
return
# pre指向当前节点
pre = cur
# 当前节点移动到下一节点;这样pre就永远指向cur的前一个节点
cur = cur.next
def search(self,item):
'''查找节点是否存在'''
cur = self.__head
# 遍历节点
while cur is not None:
if cur.item == item:
return True
# 使游标指向下一个节点
cur = cur.next
# while执行玩还没找到就是false
return False
if __name__ == '__main__':
# 创建单链表对象
sll = SingleLinkList()
# 调用各个方法
print(sll.is_empty())
sll.add(1)
sll.add(2)
sll.add(3)
sll.append(7)
sll.append(8)
sll.travel()
sll.insert(2,4)
sll.insert(3,5)
sll.insert(-1,6)
sll.insert(100,6)
sll.remove(6)
sll.remove(5)
sll.remove(3)
sll.travel()