Remove duplicates from unsorted linked list in python
Python program for Remove duplicates from unsorted linked list. Here problem description and explanation.
# Python 3 Program to
# Delete duplicate nodes in unsorted linked list
class LinkNode :
def __init__(self, data) :
self.data = data
self.next = None
class LinkedList :
# Class constructors
def __init__(self) :
self.head = None
self.tail = None
# Insert new element at end position
def insert(self, value) :
# Create new node
node = LinkNode(value)
if (self.head == None) :
# Add first node
self.head = node
else :
# Add new node at the last position
self.tail.next = node
# Make new tail
self.tail = node
# Display all node value
def display(self) :
if (self.head != None) :
print("Linked List Element : ", end = "")
temp = self.head
while (temp != None) :
# Display node value
print(temp.data, end = " ")
# Visit to next node
temp = temp.next
else :
print("Empty Linked list")
def removeNode(self) :
if (self.head == None) :
# When linked list empty
print("Empty Linked list")
else :
# Auxiliary variable
temp = self.head
hold = None
initial = None
current = None
# Outer loop
while (temp != None) :
# New last node
self.tail = temp
current = temp
initial = current.next
# Inner loop
# Remove all node which value is similar to temp node
while (initial != None) :
if (temp.data == initial.data) :
# Get remove node
hold = initial
else :
current = initial
# Visit to next node
initial = initial.next
if (hold != None) :
current.next = initial
# remove node
hold = None
# Visit to next node
temp = temp.next
def main() :
# new linked list
task = LinkedList()
# Add tested element
task.insert(1)
task.insert(2)
task.insert(9)
task.insert(4)
task.insert(9)
task.insert(3)
task.insert(1)
task.insert(7)
task.insert(2)
task.insert(1)
print("\nBefore Delete ")
task.display()
task.removeNode()
print("\nAfter Delete ")
task.display()
if __name__ == "__main__": main()
Output
Before Delete
Linked List Element : 1 2 9 4 9 3 1 7 2 1
After Delete
Linked List Element : 1 2 9 4 3 7
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment