Find kth node from end in linked list
Problem
Given a linked list find the kth node from end.
Solution
Start a pointer from head and move it k nodes. Then take another pointer from head and move them simultaneously. When the front pointer reaches end, next one will reach k nodes from end.
Code
public class LinkedListKthElementFromEnd
{
public static void main(String[] args)
{
Node head = new Node(1);
head.append(2).append(3).append(4).append(5).append(6).append(7)
.append(8).append(9);
Node result = findKFromEnd(head, 3);
System.out.println(result.value);
}
private static Node findKFromEnd(Node head, int k)
{
Node ahead = head;
while (k-- > 0)
ahead = ahead.next;
while (ahead != null)
{
head = head.next;
ahead = ahead.next;
}
return head;
}
private static class Node
{
public Node next;
public int value;
public Node(int value)
{
this.value = value;
}
public Node append(int value)
{
Node node = new Node(value);
next = node;
return node;
}
}
}