Removing duplicates from a singly linked list involves traversing the list and eliminating nodes with duplicate values. This operation ensures that each value appears only once in the list.
Consider a singly linked list with the following structure before removing duplicates:
Head -> 1 -> 2 -> 2 -> 3 -> 3 -> 4 -> None
To remove duplicates from this list, follow these steps:
After performing these steps, the linked list will have no duplicate values.
Head -> 1 -> 2 -> 3 -> 4 -> None
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def remove_duplicates(self):
if self.head is None:
return
seen = set()
current = self.head
prev = None
while current:
if current.data in seen:
prev.next = current.next
else:
seen.add(current.data)
prev = current
current = current.next
def traverse(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# Example usage:
linked_list = SinglyLinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(2)
linked_list.append(3)
linked_list.append(3)
linked_list.append(4)
print("Linked list before removing duplicates:")
linked_list.traverse() # Output: 1 -> 2 -> 2 -> 3 -> 3 -> 4 -> None
linked_list.remove_duplicates()
print("Linked list after removing duplicates:")
linked_list.traverse() # Output: 1 -> 2 -> 3 -> 4 -> None
This Python program defines a singly linked list with methods for appending nodes, removing duplicates, and traversing the list. The remove_duplicates method uses a set to keep track of seen values and removes nodes with duplicate values.