Delete middle node from linked list in python

Python program for Delete middle node from linked list. Here problem description and explanation.

#    Python 3 program for
#    Delete middle node 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
	
	#  Adding new node at beginning of linked list
	def addNode(self, data) :
		#  Create new node
		node = LinkNode(data)
		#  Connect current node to previous head
		node.next = self.head
		self.head = node
	
	#  Display linked list element
	def display(self) :
		if (self.head == None) :
			return
		
		temp = self.head
		#  iterating linked list elements
		while (temp != None) :
			#  Display node value
			print(temp.data, end = " → ")
			#  Visit to next node
			temp = temp.next
		
		print(" NULL")
	
	#  Delete the middle node of linked list
	def deleteMid(self) :
		if (self.head == None) :
			#  When linked list are no elements
			print("Empty Linked List")
		elif (self.head.next == None and self.head.next.next == None) :
			#  When linked list are less than  of 3 nodes
			print("Less then 3 node of linked list")
		else :
			temp = self.head
			midPrevious = None
			#  Find the middle and its previous node
			while (temp != None and temp.next != None and 
                   temp.next.next != None) :
				if (midPrevious == None) :
					#  When first node
					midPrevious = temp
				else :
					#  Visit to next node
					midPrevious = midPrevious.next
				
				#  Visit to next second next node
				temp = temp.next.next
			
			#  Get the node which is deleting 
			temp = midPrevious.next
			#  Show deleted node
			print("Delete node : ", temp.data)
			#  Change link
			midPrevious.next = temp.next
		
	

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

if __name__ == "__main__": main()

Output

Before Delete middle node
7 → 6 → 5 → 4 → 3 → 2 → 1 →  NULL
Delete node :  4
After Delete middle node
7 → 6 → 5 → 3 → 2 → 1 →  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