
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
Example
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
Advertisements