Was it helpful?

Question

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

PythonServer Side ProgrammingProgramming

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 −

Example

 Live Demo

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

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

   return head

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

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

Input

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

Output

3
raja
Published on 09-Oct-2020 17:58:40
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top