Delete duplicate nodes from sorted linked list in python

Python program for Delete duplicate nodes from sorted linked list. Here problem description and explanation.

#    Python 3 program for
#    Delete duplicate nodes in sorted linked list

#  Linked list node
class LinkNode :
	def __init__(self, data) :
		self.data = data
		self.next = None
	

class SingleLL :
	def __init__(self) :
		self.head = None
		self.tail = None
	
	#  Add new node at the end of linked list
	def addNode(self, value) :
		#  Create a new node
		node = LinkNode(value)
		if (self.head == None) :
			self.head = node
		else :
			self.tail.next = node
		
		self.tail = node
	
	#  Display linked list element
	def display(self) :
		if (self.head == None) :
			return
		
		temp = self.head
		#  iterating linked list elements
		while (temp != None) :
			print(temp.data , end = " → ")
			#  Visit to next node
			temp = temp.next
		
		print(" NULL")
	
	#  Remove the duplicate nodes from sorted singly linked list
	def deleteDuplicate(self) :
		if (self.head == None) :
			return
		else :
			#  Auxiliary variables
			temp = self.head.next
			current = self.head
			hold = None
			#  Find and remove duplicate
			while (temp != None) :
				#  Check duplicate node 
				if (current.data == temp.data) :
					#   When node key are same
					hold = temp
				else :
					#  When node key are not same
					current = temp
				
				#  Visit to next node
				temp = temp.next
				if (hold != None) :
					#  Modified link value
					current.next = temp
					hold = None
				else :
					#  Change last node
					self.tail = current
				
			
		
	

def main() :
	sll = SingleLL()
	#  Sorted Linked list node
	#   1 → 1 → 2 → 3 → 4 → 4 → 4 → 5 → 6 → 7 → NULL
	sll.addNode(1)
	sll.addNode(1)
	sll.addNode(2)
	sll.addNode(3)
	sll.addNode(4)
	sll.addNode(4)
	sll.addNode(4)
	sll.addNode(5)
	sll.addNode(6)
	sll.addNode(7)
	print("Before Delete")
	sll.display()
	sll.deleteDuplicate()
	print("After Delete")
	#  1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
	sll.display()

if __name__ == "__main__": main()

Output

Before Delete
1 → 1 → 2 → 3 → 4 → 4 → 4 → 5 → 6 → 7 →  NULL
After Delete
1 → 2 → 3 → 4 → 5 → 6 → 7 →  NULL


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







© 2021, kalkicode.com, All rights reserved