Remove every k th node of the linked list in python

Python program for Remove every k th node of the linked list. Here problem description and explanation.

#  Python 3 Program for
#  delete every k-th node of 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
	
	#  Add new node at the end of linked list
	def addNode(self, value) :
		#  Create  node
		node = LinkNode(value)
		if (self.head == None) :
			self.head = node
		else :
			temp = self.head
			#  Find last node
			while (temp.next != None) :
				#  Visit to next node
				temp = temp.next
			
			#  Add node at last position
			temp.next = node
		
	
	#  Display all Linked List elements
	def display(self) :
		if (self.head != None) :
			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\n")
		
	
	def removeKh(self, kth) :
		if (self.head == None) :
			#  When no element
			print("Empty Linked list")
		elif (kth <= 0) :
			print("\nInvalid position ", kth)
		else :
			temp = self.head
			hold = None
			checker = None
			count = 0
			if (kth == 1) :
				#  When delete all element
				self.head = None
			
			while (temp != None) :
				count += 1
				if (count % kth == 0) :
					#  When delete node found
					hold = temp
				else :
					#  Get current node
					checker = temp
				
				temp = temp.next
				#  When get free node
				if (hold != None) :
					if (checker != None) :
						#  Unlink node
						checker.next = hold.next
					
					hold = None
				
			
		
	

def main() :
	sll = SingleLL()
	#  Linked list
	#  1 → 2 → 3 → 4 → 5 → 6 → 7 → NULL
	sll.addNode(1)
	sll.addNode(2)
	sll.addNode(3)
	sll.addNode(4)
	sll.addNode(5)
	sll.addNode(6)
	sll.addNode(7)
	position = 2
	print("Position : ", position)
	print("Before Delete Linked List")
	sll.display()
	sll.removeKh(position)
	print("\n After Linked List")
	sll.display()

if __name__ == "__main__": main()

Output

Position :  2
Before Delete Linked List
1  2  3  4  5  6  7
 After Linked List
1  3  5  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







© 2021, kalkicode.com, All rights reserved