"""
链表就是采用链式存储实现的线性表。根据其存储结构的不同,可以分为单链表、循环链表和
双向链表三种。
"""
'''
单链表
单链表的每个结点包括两个域,分别是数据域和指针域next(指向下一个结点),最后一个结
点的指针为NULL,head表示头指针。
'''
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkList:
def __init__(self, node=None):
self.count = 0
self.head = node
def is_empty(self):
'''是否空'''
return self.head == None
def pop(self, index):
if index is None:
index = self.count -1
elif index+1 > self.count or index < 0:
raise IndexError("Index out of range")
cur = None # 游标 用来遍历结点
front_node = None # 前一个结点
for i in range(index+1): # index起步是0,要遍历到下标位置 得多遍历1次 range(2+1) >>>i = 0 1 2
if i == 0:
cur = self.head
else:
cur = cur.next
if i == index-1: # i是从0开始遍历,倒数第二次是range值 -2
front_node = cur
front_node.next = cur.next
self.count -= 1
return cur.data
def append(self, data):
'''链表尾部添加元素'''
append_node = Node(data)
if self.is_empty():
self.head = append_node
else:
cur = self.head
for i in range(self.count-1):
cur = cur.next
cur.next = append_node
self.count += 1
def insert(self, data, index):
insert_node = Node(data)
if index is None or index > self.count-1:
self.append(data)
return
if index >= self.count or index < 0:
raise IndexError("Index out of range")
cur = None # 游标 用来遍历结点
front_node = None # 前一个结点
for i in range(index+1): # index起步是0,要遍历到下标位置 得多遍历1次 range(2+1) >>>i = 0 1 2
if i == 0:
cur = self.head
else:
cur = cur.next
if i == index-1: # i是从0开始遍历,倒数第二次是range值 -2
front_node = cur
front_node.next = insert_node
insert_node.next = cur
self.count += 1
def show_list(self):
'''遍历整个列表'''
cur = self.head
while cur != None:
print(cur.data, '>>', end=' ')
cur = cur.next
print("") # 默认尾部换行符,等于输出一个 /n
if __name__ == '__main__':
linklist = LinkList()
linklist.append(1) # 尾部添加元素
linklist.append(2)
linklist.append(3)
linklist.append(4)
linklist.show_list() # 打印链表
linklist.insert('insert', 2) # 根据下标插入元素
linklist.show_list() # 打印链表
print('linklist.count----', linklist.count) # 元素个数
print('linklist.pop(4)----', linklist.pop(4)) # 按下标取出,不可超出范围
linklist.show_list()