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. p2isksteps ahead ofp1.- When
p2is at the end of linked listp1is at thekthto 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.