Delete last node of linked list in python 3

Python program for Delete last node of linked list. Here problem description and explanation.

#    Python 3 program for
#    Delete the last node of singly 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
		
		#  Set new last node
		self.tail = node
	
	#  Display linked list element
	def display(self) :
		if (self.head == None) :
			print("Empty Linked List")
			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 last node of singly linked list
	def deleteLastNode(self) :
		if (self.head == None) :
			print("Empty Linked List")
			return
		else :
			temp = self.head
			find = None
			#  Find second last node
			while (temp.next != None) :
				find = temp
				temp = temp.next
			
			if (find == None) :
				#  Delete head node of linked list
				self.head = None
				self.tail = None
			else :
				#  Set new last node
				self.tail = find
				find.next = None
			
		
	

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

if __name__ == "__main__": main()

Output

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