- Related Questions & Answers
- Python Program to Print Nth Node from the last of a Linked List
- Find the fractional (or n/k – th) node in linked list in C++
- Program to find the middle node of a singly linked list in Python
- Golang Program to delete the last node from a linked list.
- Golang Program to update the last node value in a linked list.
- Find the second last node of a linked list in single traversal in C++
- C# program to find node in Linked List
- Program for n’th node from the end of a Linked List in C program
- C# Program to add a node at the last position in a Linked List
- Python Program to Print Middle most Node of a Linked List
- 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 delete a node from the middle of the Circular Linked List
- Python program to delete a node from the end of the Circular Linked List
- Python program to find the maximum and minimum value node from a doubly linked list

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

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

3

Advertisements