无序列表的实现, 也是主要理解指针移动过程即可, 这些线性结构都是相似的.
# 简单地解释一下, 然后重点是上代码即可.
1 """
2 无序列表-链表
3 被构造项的集合, 每个项保持相对于其他项的相对位置, 链式存储
4
5 结构:
6 节点: 包含 数据区 和指针区 (存储下一个元素的位置, 或指向下元素)
7 链式存储: 节点之间, 通过指针进行连接
8
9 思路:
10 节点: 既然包含多种成分, 自然想到用 Class 去封装呀
11 指针: Python中没有指针的概念, 其实 "=" 就是"指向"的概念;
12 即, Python中的变量, 就是 C 语言中的指针, 存的不是值, 而是指向变量的地址
13 因此 Python 的变量不需要声明, 直接指向即可, 因为它并没有存值,而是存指针
14
15 """
16
17
18 class Node:
19 """节点类"""
20
21 def __init__(self, init_data):
22 self.data = init_data
23 self.next = None
24
25
26 class UnorderedList:
27 def __init__(self):
28 self.head = None
29
30 def is_empty(self):
31 return self.head is None
32
33 def add(self, item):
34 """链表头部插入元素节点"""
35 node = Node(item)
36 # 建议画图来理解指针 连接 和 断链 过程
37
38 # 1. 先让 node的指针next 指向 head
39 node.next = self.head
40 # 2. 再让 head 指向node
41 self.head = node
42
43 def size(self):
44 """遍历节点,并统计节点个数"""
45 count = 0
46 # 构建一个游标 current ,初始指向头节点, 然后依次往后移
47 current = self.head
48 while current is not None:
49 count += 1
50 current = current.next # 游标移动
51
52 return count
53
54 def search(self, item):
55 """检测元素是否在链表中"""
56 current = self.head
57 while current is not None:
58 # 每移动一次游标, 就取该节点值与判断值进行比较
59 if current.data == item:
60 return True
61 current = current.next # 游标往后移动
62
63 return False
64
65 def remove(self, item):
66 """删除节点"""
67 current = self.head
68 prior = None # 跟随current, 指向其前一个节点
69
70 found = False # 标记是否找到
71 while not found:
72 # 移动游标, 然后查找到了就退出循环
73 if current.data == item:
74 found = True
75 else:
76 # 没有找到则, prior先指向 current, 然后每当current 先移动一次,piror也跟着移一次
77 prior = current
78 current = current.next
79
80 # 如果要删除的是 头节点, 则将头结点指向,被删的下一个节点
81 if prior is None:
82 self.head = current.next
83 else:
84 # 直接让 prior 去指向 current.next 就删了
85 prior.next = current.next
86
87
88
89
90 if __name__ == '__main__':
91 # test
92 my_list = UnorderedList()
93
94 my_list.add(666)
95 my_list.add(999)
96 my_list.add(888)
97
98 print(my_list.size())
99 print(my_list.search(999))
100
101 my_list.remove(999)
102 print(my_list.search(999))
输出:
3
True
False
这块相对简单, 也仅是做个记录而已, 主要是怕自己突然给忘记了.
耐心和恒心, 总会获得回报的.