Insert linked list node at nth last position in python

Python program for Insert linked list node at nth last position. Here problem description and explanation.

#  Python 3 program for
#  Insert linked list node at nth last position 

#  Linked list node
class LinkNode :
	def __init__(self, data) :
		self.data = data
		self.next = None
	

class LinkedList :
	def __init__(self) :
		self.head = None
	
	#  insert node at end position
	def insert(self, value) :
		#  Create a new node
		node = LinkNode(value)
		if (self.head == None) :
			self.head = node
		else :
			temp = self.head
			#  Find the last node
			while (temp.next != None) :
				#  Visit to next node
				temp = temp.next
			
			#  Add node
			temp.next = 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")
	
	#  Add node at specific position from the end of linked list
	def endPosition(self, position, value) :
		if (self.head == None) :
			print("Empty Linked list")
		elif (position <= 0) :
			print("Invalid position")
		else :
			temp = self.head
			location = None
			while (temp != None) :
				position -= 1
				if (position <= 0) :
					if (location == None) :
						location = self.head
					else :
						location = location.next
					
				
				#  visit to next node
				temp = temp.next
			
			if (position <= 1) :
				node = LinkNode(value)
				if (location == None) :
					#  Add node at first place
					node.next = self.head
					self.head = node
				else :
					#  Add node at intermediate position
					node.next = location.next
					location.next = node
				
			else :
				print("Opps position not found")
			
		
	

def main() :
	sll = LinkedList()
	#  Add node
	sll.insert(5)
	sll.insert(4)
	sll.insert(3)
	sll.insert(2)
	sll.insert(1)
	sll.display()
	position = 2
	data = 10
	sll.endPosition(position, data)
	print(" Add", data ," at last", position ,"-nd position")
	sll.display()

if __name__ == "__main__": main()

Output

5 → 4 → 3 → 2 → 1 → NULL
 Add 10  at last 2 -nd position
5 → 4 → 3 → 2 → 10 → 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