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): self.data = data self.next = None def takeinput(): head = None tail = None L = [int(i) for i in input().split()] for i in L: if i == -1: break NewNode = node(i) if head == None: head = NewNode tail = NewNode else: tail.next = NewNode tail = NewNode return head def printLinkedList(head): while head != None: print(head.data,end=' ') head = head.next def removeDuplicates(head): if head == None: return curr = head after = head.next while curr != None: if after == None: curr.next = None break if after.data != curr.data: curr.next = after curr = after after = after.next return head Head = takeinput() Head = removeDuplicates(Head) printLinkedList(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.