Skip to main content

Find second last element of linked list in python

Python program for Find second last element of linked list. Here problem description and explanation.

#  Python 3 program for
#  Find the second last node of a linked list

#  Node of Linked List
class LinkNode :
	def __init__(self, data) :
		#  Set node value
		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 insert(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")
	
	# Find the second last node of a linked list
	def secondLast(self) :
		node = self.head
		if (node == None) :
			print("Empty linked list")
		elif (node.next == None) :
			print("Only one node in this linked list")
		else :
			#  Find second last node
			while (node.next != None and node.next.next != None) :
				#  Visit to second next node
				node = node.next.next
			
			print("Second last element is : ", node.data)
		
	

def main() :
	sll = SingleLL()
	#  Add linked list node
	sll.insert(6)
	sll.insert(3)
	sll.insert(2)
	sll.insert(7)
	sll.insert(1)
	sll.insert(9)
	print("Linked List")
	#  6 → 3 → 2 → 7 → 1 → 9 → null
	sll.display()
	sll.secondLast()

if __name__ == "__main__": main()

Output

Linked List
6  → 3  → 2  → 7  → 1  → 9  → null
Second last element is :  1




Comment

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