Delete a node from linked list specific position in python

Python program for Delete a node from linked list specific position. Here problem description and explanation.

#  Python 3 Program for
#  Delete node at given index of 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")
	
	#  Delete node at given position
	def deleteAtIndex(self, index) :
		temp = self.head
		if (self.head == None) :
			print("Empty linked list")
			return
		elif (index < 0) :
			print("Invalid positions")
			return
		elif (index == 1) :
			#  Means deleting a first node
			if (self.tail == self.head) :
				#  Only one node
				self.tail = None
			
			#  Make second node as head
			self.head = self.head.next
		else :
			count = index - 1
			#  iterating linked list elements and find deleted node
			while (temp != None and count > 1) :
				#  Visit to next node
				temp = temp.next
				count -= 1
			
			if (count == 1 and temp.next != None) :
				#  Get deleted node
				n = temp.next
				if (n == self.tail) :
					#  When delete last node
					self.tail = temp
				
				#  Unlink the deleting node
				temp.next = n.next
			else :
				print(" Index ", index ," are not present")
				return
			
		
	

def main() :
	sll = SingleLL()
	#  Test with your index
	#  Note index start with 1
	index = 5
	#  Linked list
	#  10 → 20 → 30 → 40 → 50 → 60 → 70 → 80 → NULL
	sll.addNode(10)
	sll.addNode(20)
	sll.addNode(30)
	sll.addNode(40)
	sll.addNode(50)
	sll.addNode(60)
	sll.addNode(70)
	sll.addNode(80)
	print(" Before Delete Linked List")
	sll.display()
	#  Delete node at 5-th position
	sll.deleteAtIndex(index)
	#  Display linked list
	print(" After Delete Linked List")
	sll.display()

if __name__ == "__main__": main()

Output

 Before Delete Linked List
10  → 20  → 30  → 40  → 50  → 60  → 70  → 80  → NULL
 After Delete Linked List
10  → 20  → 30  → 40  → 60  → 70  → 80  → 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