Find the kth to last element of a singly linked list
Problem description :
Implement a non-recursive algorithm to find the kth to last element of a singly linked list.
Input : A linked list
Output : A value of a node in a linked list
Logic :
- Iterate through the list with two pointers
p1
,p2
. p2
isk
steps ahead ofp1
.- When
p2
is at the end of linked listp1
is at thekth
to last element of a singly linked list.
This post is a follow-up of JavaScript Linked List Example. I recommend reading that first, as the following code uses the method from it.