- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
- Related Articles
- Remove Every K-th Node Of The Linked List
- Find the fractional (or n/k – th) node in linked list in C++
- Python Program to Print Nth Node from the last of a Linked List
- Golang Program to delete the last node from a linked list.
- Golang Program to update the last node value in a linked list.
- Program to find the middle node of a singly linked list in Python
- C# Program to add a node at the last position in a Linked List
- C# program to find node in Linked List
- Find the second last node of a linked list in single traversal in C++
- Remove Last Node of the Linked List using C++
- Golang program to insert a new node after the Kth node (K is not in the linked list)
- Golang Program to delete the node after the Kth node (K is not in the linked list).
- Python Program to Print Middle most Node of a Linked List
- Python program to find the maximum and minimum value node from a doubly linked list
- Python program to find the maximum and minimum value node from a circular linked list

Advertisements