Remove Duplicates from Sorted List

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Solution

Double Pointer / Fast And Slow Pointer

Code

  • submit code
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # Base Condition
        if head == None:
            return head

        fast = head
        slow = head

        while fast != None:
            if fast.val != slow.val:
                # important
                slow = slow.next
                slow.val = fast.val
            fast = fast.next

        slow.next = None
        return head
  • full code to understand
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def deleteDuplicates(self, head):
        listN = ListNode(head[0])
        tmp = listN
        # Create ListNode From head list
        for m in range(1,head.__len__()):
            listN.next = ListNode(head[m])
            listN = listN.next


        fast = tmp
        slow = tmp

        while fast != None:
            if fast.val != slow.val:
                slow = slow.next
                slow.val = fast.val
            fast = fast.next

        slow.next = None


        return tmp


head = [1,1,2,3,4,5,5]
# head = [1,1,2,2]

S = Solution()
ret = S.deleteDuplicates(head)
while ret != None:
    print(ret.val)
    ret = ret.next

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *