Remove duplicates from sorted Linked List in Python

Here in this tutorial, we will learn how to remove duplicates from a linked list in Python.

From a linked list like this:

1 2 2 3 4 4 5

To a linked list like:

1 2 3 4 5

In a linked list elements are connected via references. The first element will store the reference to the second, the second will store the third, and so on.

Removing duplicates in a linked list

This will be followed by the basic implementation of the linked list. below is the given Python program:

class node:
    def __init__(self, data): = data = None
def takeinput():
    head = None
    tail = None
    L = [int(i) for i in input().split()]
    for i in L:
        if i == -1:
        NewNode = node(i)
        if head == None:
            head = NewNode
            tail = NewNode
   = NewNode
            tail = NewNode
    return head

def printLinkedList(head):
    while head != None:
        print(,end=' ')
        head =
def removeDuplicates(head):
    if head == None:
    curr = head
    after =
    while curr != None:
        if after == None:
   = None
        if !=
   = after
            curr = after
        after =
    return head
Head = takeinput()
Head = removeDuplicates(Head)


> 1 2 2 3 4 4 5
1 2 3 4 5

In the code written above, we have used the function removeDuplicates() which will first check if the head is empty/None if it is then it will return.

Next,  we have taken a variable ‘curr’ and ‘after’ which will keep track of two consecutive numbers.

Then within the while loop, we will check if after is None or not and change the value of the next of curr accordingly. Moving forward we will check if the values at the two places nodes match if they do then we will change the references accordingly and return the head at the end.

Thus we have seen how removing duplicates is implemented in Python.

Leave a Reply

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