Python中如何删除链表中的重复节点

2023-04-11 00:00:00 节点 重复 链表

可以使用哈希表来存储已经出现过的节点,如果节点在哈希表中出现过,则将该节点删除,否则将该节点加入哈希表中。

以下是具体实现代码:

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def delete_duplicates(head: ListNode) -> ListNode:
    if not head:
        return head

    seen = set()
    prev, curr = None, head

    while curr:
        if curr.val in seen:
            prev.next = curr.next
        else:
            seen.add(curr.val)
            prev = curr
        curr = curr.next

    return head

使用样例:

# 构造链表
node_1 = ListNode('p')
node_2 = ListNode('i')
node_3 = ListNode('d')
node_4 = ListNode('a')
node_5 = ListNode('n')
node_6 = ListNode('c')
node_7 = ListNode('o')
node_8 = ListNode('d')
node_9 = ListNode('e')
head = node_1
node_1.next = node_2
node_2.next = node_3
node_3.next = node_4
node_4.next = node_5
node_5.next = node_6
node_6.next = node_7
node_7.next = node_8
node_8.next = node_9

# 删除重复节点
new_head = delete_duplicates(head)

# 遍历链表
curr = new_head
while curr:
    print(curr.val, end='')
    curr = curr.next

输出结果为:

pidancod程

相关文章