1. Create a LinkedList
class ListNode(object):
def __init__(self, val):
self.val = val
self.next = None
def buildList(seq):
# seq is a list of objects.
f = ListNode(None)
c = f
for obj in seq:
c.next = ListNode(obj)
c = c.next
return f.next
# Test
h = buildList([1, 2, 3, 4])2. Traverse
def print_all_nodes(head):
while head:
print(head.val, end=' ')
head = head.next
# Test
print_all_nodes(h)1 2 3 4
3. Search
3.1 Search by index
def search_by_index(head, index):
if not head or index < 0:
return None
for _ in range(index):
head = head.next
if not head:
return None
return head
# Test
rst = search_by_index(h, 2)
print(rst.val)3
3.2 Search by value
def search_by_value(head, val):
if not head:
return head
curr_node = head
while curr_node:
if curr_node.val == val:
return curr_node
curr_node = curr_node.next
return None
# Test
rst = search_by_value(h, 2)
print(rst.val)2
4. Compare
4.1 未重写 __eq__ 的 ListNode 默认按对象身份比较
n1, n2 = ListNode(1), ListNode(1)
print(n1 == n2) # Two independent objects while contain the same content
print(id(n1) == id(n2))False
False
4.2 _eq_:Define our own equality comparison logic
class ListNodeNew(object):
def __init__(self, val):
self.val = val
self.next = None
def __eq__(self, other):
return isinstance(other, ListNodeNew) and self.val == other.val
# Test
n1_new, n2_new = ListNodeNew(1), ListNodeNew(1)
print(n1_new == n2_new)True
整理注: 这里的
ListNodeNew.__eq__仅比较val,不递归比较next,因此不能用来判断整条链表是否相同。对象身份应使用is;id()不应一概解释为所有 Python 实现中的物理内存地址。
5. Add
5.1 分情况考虑
def add_to_index(head, index, value):
if index == 0:
new_head = ListNode(value)
new_head.next = head
return new_head
else:
prev_node = search_by_index(head, index - 1)
if not prev_node:
return head
new_node = ListNode(value)
new_node.next = prev_node.next
prev_node.next = new_node
return head# Test
h = buildList([1, 2, 3, 4])
h_new = add_to_index(h, 0, 'zero') # h != h_new
print_all_nodes(h)
print()
print_all_nodes(h_new)
print('\n')
h = buildList([1, 2, 3, 4])
h_new = add_to_index(h, 1, 'one') # h == h_new
print_all_nodes(h)
print()
print_all_nodes(h_new)1 2 3 4
zero 1 2 3 4
1 one 2 3 4
1 one 2 3 4
5.2 Fake head
def add_to_index_fake(head, index, val):
fake_head = ListNode(None)
fake_head.next = head
insert_place = search_by_index(fake_head, index)
if insert_place is None:
return fake_head.next
new_node = ListNode(val)
new_node.next = insert_place.next
insert_place.next = new_node
return fake_head.next# Test
h = buildList([1, 2, 3, 4])
h_new = add_to_index_fake(h, 0, 'zero') # h != h_new
print_all_nodes(h)
print()
print_all_nodes(h_new)
print('\n')
h = buildList([1, 2, 3, 4])
h_new = add_to_index_fake(h, 1, 'one') # h == h_new
print_all_nodes(h)
print()
print_all_nodes(h_new)1 2 3 4
zero 1 2 3 4
1 one 2 3 4
1 one 2 3 4
6. Remove
def remove_from_index(head, index):
fake_head = ListNode(None)
fake_head.next = head
remove_place = search_by_index(fake_head, index)
if remove_place is None or remove_place.next is None:
return fake_head.next
remove_node = remove_place.next
remove_place.next = remove_node.next
remove_node.next = None
return fake_head.next# Test
h = buildList([1, 2, 3, 4])
h_new = remove_from_index(h, 0) # h != h_new
print_all_nodes(h)
print()
print_all_nodes(h_new)
print('\n')
h = buildList([1, 2, 3, 4])
h_new = remove_from_index(h, 1) # h == h_new
print_all_nodes(h)
print()
print_all_nodes(h_new)1
2 3 4
1 3 4
1 3 4
整理注: 删除函数会将被移除节点的
next断开。删除头节点后,旧变量h仍指向被移除节点,所以原输出的第一行只打印1;新链表应使用返回的h_new。
7. Difference between Python list and singly linked list
独立重绘:把尾部追加和删除分开,注明摊还复杂度与单链表假设。
整理注: 表中按索引插删包含找到位置的成本;若已持有前驱节点,单链表的指针修改本身为
O(1)。Python 列表尾部操作标记为摊还复杂度。