Remove Duplicates from Sorted List

Question

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

For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3.

Tag

  • Linked List

Thought

Just use the straightforward approach: Looping from the head node until the tail node and skip all the duplicated nodes when concatenate the nodes with previous pointer and the current pointer.

Code

# 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 head is None:
            return head
        prev, ptr = head, head.next
        while ptr is not None:
            if prev.val == ptr.val:
                ptr = ptr.next
            else:
                prev.next = ptr
                prev = prev.next
                ptr = ptr.next
        prev.next = None
        return head

results matching ""

    No results matching ""