In this program we will see that how can we remove duplicate element from Linked List after sorting it
class Node: def __init__(self,data): self.data = data self.next = None
class LinkedList: def __init__(self): self.head = None
def display(self): temp = self.head while temp!=None: print(temp.data,end="=>") temp = temp.next def length(self): temp = self.head count = 0 while temp!=None: count = count+1 temp = temp.next return count def sort(self): temp = self.head count = 0 while count<self.length(): temp1 = temp while temp1.next!=None: if temp1.next.data<temp1.data: hold = temp1.next.data temp1.next.data = temp1.data temp1.data = hold temp1 = temp1.next else: temp1 = temp1.next count = count+1
def removeDuplicate(self): temp = self.head while temp!=None: temp1=temp while temp1.next!=None: dup = temp1.next if temp.data==temp1.next.data: dup = temp1.next.next temp1.next = dup del dup else: temp1 = temp1.next temp = temp.next
if __name__ == "__main__": llist = LinkedList() first = Node(50) second = Node(10) third = Node(20) fourth = Node(10) fifth = Node(10) llist.head = first first.next = second second.next = third third.next = fourth fourth.next = fifth llist.display() llist.sort() llist.removeDuplicate() print("\nAfter sorting and removing duplicates") llist.display()
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def display(self):
temp = self.head
while temp!=None:
print(temp.data,end="=>")
temp = temp.next
def length(self):
temp = self.head
count = 0
while temp!=None:
count = count+1
temp = temp.next
return count
def sort(self):
temp = self.head
count = 0
while count<self.length():
temp1 = temp
while temp1.next!=None:
if temp1.next.data<temp1.data:
hold = temp1.next.data
temp1.next.data = temp1.data
temp1.data = hold
temp1 = temp1.next
else:
temp1 = temp1.next
count = count+1
def removeDuplicate(self):
temp = self.head
while temp!=None:
temp1=temp
while temp1.next!=None:
dup = temp1.next
if temp.data==temp1.next.data:
dup = temp1.next.next
temp1.next = dup
del dup
else:
temp1 = temp1.next
temp = temp.next
if __name__ == "__main__":
llist = LinkedList()
first = Node(50)
second = Node(10)
third = Node(20)
fourth = Node(10)
fifth = Node(10)
llist.head = first
first.next = second
second.next = third
third.next = fourth
fourth.next = fifth
llist.display()
llist.sort()
llist.removeDuplicate()
print("\nAfter sorting and removing duplicates")
llist.display()