简体   繁体   中英

What is wrong in my code...Remove duplicates from an unsorted linked list

Remove duplicates from an unsorted linked list

Given an unsorted linked list of N nodes. The task is to remove duplicate elements from this unsorted Linked List. When a value appears in multiple nodes, the node which appeared first should be kept, all others duplicates are to be removed.

Example 1:

Input:

N = 4

value[ ] = {5,2,2,4}

Output: 5 2 4

Example 2:

Input :

N = 5

value[] = {2,2,2,2,2}

Output: 2

My Code

def removeDuplicates(head):
        if head is None or not head.next:
            return head
        d = {}
        curr = head
        prev = None
        
        while curr.next:
            
            prev = curr
            curr = curr.next
            if curr.data in d:
                prev.next = curr.next
            else:
                d[curr.data] = 1
        return head

In your while loop as condition you need curr instead of curr.next . And you need to overwrite curr at the end of the while loop. Like this:

def removeDuplicates(head):
    if head is None or not head.next:
        return head
    d = {}
    curr = head
    prev = None
    while curr:
        if curr.data in d:
            prev.next = curr.next
        else:
            d[curr.data] = 1
            prev = curr
        curr = curr.next
    return head

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM