TABLE OF CONTENT


remove-duplicates-from-unsorted-list

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: The first node of linked list.
    @return: Head node.
    """
    def removeDuplicates(self, head):
        # write your code here
        d={}    # count each node values

        # if no node or just one node, nothing to do
        if not head or not head.next: return head

        # if there are at least 2 nodes, count first node
        p=head; d[head.val]=1
        # and keep checking next node
        while p.next:
            # count next node value
            d[p.next.val]=d.get(p.next.val,0)+1
            # if next node is seen, skip it
            if d[p.next.val]>=2:
                p.next=p.next.next
            else:
                p=p.next
        return head


blog comments powered by Disqus

Published

30 December 2019

Tags