In: Computer Science
Given a linked list of integers, remove any nodes from the linked list that have values that have previously occurred in the linked list. Your function should return a reference to the head of the updated linked list. (In Python)
Program in Python:-
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# This function to initialize head
def __init__(self):
self.head = None
#This function is used to insert a
# new node at the beginning
def insert(self, data):
node = Node(data)
node.next=self.head
self.head = node
#This function to print the LinkedList
def printList(self):
current = self.head
while current:
print(current.data,end=" ")
current= current.next
#This function is used to removes duplicates
#elements from the LinkedList
def removeDuplicates(self):
temp = ptr = self.head
while temp is not None: #Pick elements one by one
# Compare the picked element with rest of the elements in the LinkedList
while ptr.next is not None:
# If duplicate element find then delete it
if ptr.next.data == temp.data:
ptr.next = ptr.next.next
else:
ptr = ptr.next
temp = temp.next
ptr = temp
l= LinkedList()
l.insert(10)
l.insert(20)
l.insert(30)
l.insert(20)
l.insert(15)
l.insert(10)
l.insert(20)
l.insert(40)
l.insert(30)
print("Elements of LinkedList before removing duplicate elements: ")
l.printList()
l.removeDuplicates()
print("\nElements of LinkedList after removing duplicate elements: ")
l.printList()
Output:-