Posted on by Kalkicode
Code Doubly linked list

Remove duplicates from sorted doubly linked list in python

Python program for Remove duplicates from sorted doubly linked list. Here problem description and explanation.

#  Python 3 program for
#  Remove duplicates from sorted doubly linked list 
class LinkNode :
	def __init__(self, data) :
		self.data = data
		self.next = None
		self.prev = None
	

class DoublyLinkedList :
	def __init__(self) :
		self.head = None
	
	#  Insert new node at end position
	def insert(self, value) :
		#  Create a node
		node = LinkNode(value)
		if (self.head == None) :
			#  Add first node
			self.head = node
			return
		
		temp = self.head
		#  Find last node
		while (temp.next != None) :
			#  Visit to next node
			temp = temp.next
		
		#  Add node at the end position
		temp.next = node
		node.prev = temp
	
	#  Display node element of doubly linked list
	def display(self) :
		if (self.head == None) :
			print("Empty Linked List")
		else :
			print("Doubly Linked List Element :", end = "")
			#  Get first node of linked list
			temp = self.head
			#  iterate linked list 
			while (temp != None) :
				#  Display node value
				print(" ", temp.data, end = " ")
				#  Visit to next node
				temp = temp.next
			
		
	
	#  Delete duplicates from doubly linked list 
	def removeNode(self) :
		if (self.head != None) :
			find = None
			#  Get second node
			node = self.head.next
			#  Iterating linked list and remove duplicate nodes
			while (node != None) :
				#  Duplicate nodes
				if (node.prev.data == node.data) :
					#  When we are gets a similar node
					find = node
				
				#  Visit to next node
				node = node.next
				if (find != None) :
					#  Rebuild the connection of before and 
					#  after deleted node.
					if (find.prev != None) :
						#  When previous node exists
						find.prev.next = node
					
					if (node != None) :
						#  When next node exists
						node.prev = find.prev
					
					#  Unlink
					#  remove element
					find.prev = None
					find.next = None
					find = None
				
			
		
	

def main() :
	dll = DoublyLinkedList()
	#  Insert following linked list nodes
	dll.insert(5)
	dll.insert(5)
	dll.insert(7)
	dll.insert(9)
	dll.insert(9)
	dll.insert(9)
	dll.insert(11)
	dll.insert(45)
	dll.insert(45)
	print("Before delete duplicates ")
	#  Display all node
	dll.display()
	print("\nAfter delete duplicates ")
	dll.removeNode()
	dll.display()

if __name__ == "__main__": main()

Output

Before delete duplicates
Doubly Linked List Element :  5   5   7   9   9   9   11   45   45
After delete duplicates
Doubly Linked List Element :  5   7   9   11   45

Comment

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