Remove duplicates from sorted list

Given a sorted linked list, delete all duplicates such that each element appear onlyonce.

For example, Given1->1->2, return1->2. Given1->1->2->3->3, return1->2->3.

Idea: Use 2 pointers and keep re-adjusting the pointers. Be careful with the base cases.

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return []

        firstPtr = head
        secondPtr = head.next
        while secondPtr is not None:
            if secondPtr.val != firstPtr.val:
                firstPtr.next = secondPtr
                firstPtr = secondPtr

            secondPtr = secondPtr.next
        # Now point firstPtr.next to secondPtr (== None, at this point)    
        firstPtr.next = secondPtr

        return head

Last updated

Was this helpful?