Program to find the K-th last node of a linked list in Python

Suppose we have a singly linked list, we have to check find the value of the kth last node (0-indexed). We have to solve this in single pass.

So, if the input is like node = [5,4,6,3,4,7], k = 2, then the output will be 3, as The second last (index 3) node has the value of 3.

To solve this, we will follow these steps −

  • klast := node

  • last := node

  • for i in range 0 to k, do

    • last := next of last

  • while next of last is not null, do

    • last := next of last

    • klast := next of klast

  • return value of klast

Let us see the following implementation to get better understanding −


 Live Demo

class ListNode:
   def __init__(self, data, next = None):
      self.val = data = next

def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
         ptr = = ListNode(element)

   return head

class Solution:
   def solve(self, node, k):
      klast = node
      last = node
      for i in range(k):
         last =
         last =
         klast =
      return klast.val

ob = Solution()
l1 = make_list([5,4,6,3,4,7])
print(ob.solve(l1, 2))


[5,4,6,3,4,7], 2



Updated on: 09-Oct-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started