CA 23 - Remove Duplicates in Sorted Linked List

 Remove Duplicates from a Sorted Linked List

Given a singly linked list. The task is to remove duplicates (nodes with duplicate values) from the given list (if it exists).
Note: Try not to use extra space. The nodes are arranged in a sorted way.

Examples:

Input:
LinkedList: 2->2->4->5
Output: 2 -> 4 -> 5
Explanation: In the given linked list 2 -> 2 -> 4 -> 5, only 2 occurs more than 1 time. So we need to remove it once.
Input:
LinkedList: 2->2->2->2->2
Output: 2
Explanation: In the given linked list 2 -> 2 -> 2 -> 2, 2 is the only element and is repeated 5 times. So we need to remove any four 2.

Expected Time Complexity : O(n)
Expected Space 
Complexity: O(1)

Constraints:
1 <= Number of nodes, data of nodes <= 10

My CODE:
def removeDuplicates(head):
    curr= head
    while curr and curr.next:
        if curr.data == curr.next.data:
            curr.next = curr.next.next
        else:
            curr = curr.next
    return head

Comments

Popular posts from this blog

CA 22 - Reverse a Linked List