算法与数据结构 / 13

单链表:创建、查找与增删

节点构造、遍历、查找、对象比较与虚拟头节点。

1. Create a LinkedList

PYTHON · 仅供阅读
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

PYTHON · 仅供阅读
def print_all_nodes(head):
    while head:
        print(head.val, end=' ')
        head = head.next

        
# Test
print_all_nodes(h)
原笔记输出 · 本次未执行
1 2 3 4

3.1 Search by index

PYTHON · 仅供阅读
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

PYTHON · 仅供阅读
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 默认按对象身份比较

PYTHON · 仅供阅读
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

PYTHON · 仅供阅读
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

TC={O(1)if headO(n)if otherTC = \begin{cases} O(1) & \text{if head} \\ O(n) & \text{if other} \\ \end{cases}

5.1 分情况考虑

PYTHON · 仅供阅读
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
PYTHON · 仅供阅读
# 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

PYTHON · 仅供阅读
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
PYTHON · 仅供阅读
# 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

PYTHON · 仅供阅读
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
PYTHON · 仅供阅读
# 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

Python 列表与仅维护头指针的单链表复杂度对比

独立重绘:把尾部追加和删除分开,注明摊还复杂度与单链表假设。

整理注: 表中按索引插删包含找到位置的成本;若已持有前驱节点,单链表的指针修改本身为 O(1)。Python 列表尾部操作标记为摊还复杂度。

整理参考资料