Skip to main content

First duplicate element of a linked list in python

Python program for First duplicate element of a linked list. Here more information.

#  Python 3 program for
#  Find the first duplicate element in the 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
	
	def insert(self, data) :
		node = LinkNode(data)
		if (self.head == None) :
			#  Add first node
			self.head = node
		else :
			#  Add node at the end position
			self.tail.next = node
		
		#  New last 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")
	
	#  Find first repeating element 
	#  from front to end in a linked list
	#  Solution are takes O(n*n) time
	def firstDuplicate(self) :
		print()
		#  Display linked list elements
		self.display()
		#  Define some auxiliary variables
		outer = self.head
		inner = None
		result = None
		#  iterating linked list elements
		while (outer != None and result == None) :
			#  Get next node
			inner = outer.next
			#  iterating linked list elements 
			#  from current node to end
			while (inner != None and result == None) :
				if (inner.data == outer.data) :
					#  When get first duplicate node exist
					result = outer
				
				inner = inner.next
			
			#  Visit to next node
			outer = outer.next
		
		if (result == None) :
			print(" First duplicate : None")
		else :
			print(" First duplicate : ", result.data)
		
	

def main() :
	list1 = SingleLL()
	list2 = SingleLL()
	list3 = SingleLL()
	#  Add node in first linked list
	list1.insert(6)
	list1.insert(4)
	list1.insert(5)
	list1.insert(9)
	list1.insert(3)
	list1.insert(5)
	list1.insert(4)
	list1.insert(9)
	#  Add node in second linked list
	list2.insert(6)
	list2.insert(2)
	list2.insert(3)
	list2.insert(3)
	list2.insert(2)
	list2.insert(5)
	list2.insert(3)
	#  Add node in third linked list
	list3.insert(2)
	list3.insert(1)
	list3.insert(8)
	list3.insert(4)
	#  Test
	list1.firstDuplicate()
	list2.firstDuplicate()
	list3.firstDuplicate()

if __name__ == "__main__": main()

Output

 6 → 4 → 5 → 9 → 3 → 5 → 4 → 9 → NULL
 First duplicate :  4

 6 → 2 → 3 → 3 → 2 → 5 → 3 → NULL
 First duplicate :  2

 2 → 1 → 8 → 4 → NULL
 First duplicate : None




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