Remove duplicate Circular Linked list

删除所有的重复节点,有两种问题,第一个是仅仅删除重复的,第二种删除全部节点。要确定的事链表事排序的,如果不是排序的就用hastable去做。

https://www.geeksforgeeks.org/remove-duplicates-from-an-unsorted-linked-list/

1->1->2->3->1

(1) 保留一个节点,删除多余的重复节点,

def delDuplicate(head):
    if head == None or head.next == None:
        return head
    dummy = LinkedList(0)
    dummy = head

    while head and head.next:
        if head.val == head.next.val:
            head = head.next.next
        else:
            head = head.next
        if head == dummy:
            break
    return dummy

(2) 一个节点也不保留,全部删除。

def delDuplicate(head):
    if head == None or head.next == None:
        return head
    dummy = LinkedList(0)
    dummy.next = head
    head = dummy

    while head and head.next:
        if head.next.val == head.next.next.val:
            val = head.next
            while head.next and head.next.val == val:
                head.next = head.next.next
        else:
            head = head.next

Last updated

Was this helpful?