Find the k-th Node from the End of a Linked List

Given the head node of a singly linked list and an integer 'k', this problem requires you to determine the value at the k-th node from the end of the linked list.

Example:

For a given linked list image, if k=2, the value at the second node from the end is 12.

Input:

The first line of the input contains an integer T representing the number of test cases.
For each test case, the first line contains integers denoting the nodes of the linked list, ending with -1 to signify the end of the list.
The second line contains an integer k.

Output:

For each test case, return a pointer to the node at the k-th position from the end of the linked list.

Constraints:

  • 1 <= T <= 50
  • 0 <= N <= 10^5
  • -10^9 <= data <= 10^9
  • 1 <= k <= N
  • node->data ≠ -1
Note:
1. You don't need to handle the input. It's managed already. Simply implement the function to return a pointer to the k-th node from the end of the list.
2. It is guaranteed that k <= the size of the linked list.
AnswerBot
12d

To find the k-th node from the end of a linked list, iterate through the list to determine the size, then traverse again to reach the k-th node from the end.

  • Iterate through the linked list to determin...read more

Help your peers!
Add answer anonymously...
Uber Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter