package chapter_2;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

/**
 * Question 2.2: Implement an algorithm to find the kth to last element of a
 * single linked list
 * 
 * @author Sudharsanan Muralidharan
 */
public class KthToLast {

  private int findElement(CustomLinkedList<Integer> list, int k) {
    Node<Integer> current = list.head();
    int i = 0;
    
    while(current != null) {
      if(i == list.size() - k) {
        return current.data;
      }
      i++;
      current = current.next;
    }
    
    return -1;
  }

  public static void main(String[] args) throws FileNotFoundException {
    FileReader fileReader = new FileReader("input_files/chapter_2/k_last");
    Scanner scanner = new Scanner(fileReader);
    KthToLast kthToLast = new KthToLast();
    String input;
    String[] elements;
    int k;

    while (scanner.hasNextLine()) {
      input = scanner.nextLine();
      k = Integer.parseInt(input.split(" ")[0]);
      elements = input.split(" ")[1].split(":");
      CustomLinkedList<Integer> list = new CustomLinkedList<Integer>();
      for (String e : elements) {
        list.add(Integer.parseInt(e));
      }

      System.out.println("Value of K:" + k);
      System.out.println("Linked List:");
      list.print();

      System.out.print("Element at k from last: " + kthToLast.findElement(list, k) + "\n");
      System.out.println();
    }

    scanner.close();
  }
}

@@ -401,20 +401,16 @@
  i = 0;%0A
-    
 %0A    whi
@@ -411,16 +411,17 @@
    while
+ 
 (current
@@ -440,16 +440,17 @@
       if
+ 
 (i == li
@@ -462,16 +462,20 @@
 ze() - k
+ - 1
 ) %7B%0A    
@@ -554,20 +554,16 @@
 ;%0A    %7D%0A
-    
 %0A    ret
@@ -575,16 +575,359 @@
 1;%0A  %7D%0A%0A
+  private int findElement2(CustomLinkedList%3CInteger%3E list, int k) %7B%0A    Node%3CInteger%3E current = list.head();%0A    Node%3CInteger%3E runner = current;%0A%0A    for (int i = 0; i %3C k + 1; i++) %7B%0A      runner = runner.next;%0A    %7D%0A%0A    while (runner != null) %7B%0A      current = current.next;%0A      runner = runner.next;%0A    %7D%0A%0A    return current.data;%0A  %7D%0A%0A
   public
@@ -1727,24 +1727,128 @@
 k) + %22%5Cn%22);%0A
+      System.out.print(%22Element at k from last - Method 2: %22 + kthToLast.findElement2(list, k) + %22%5Cn%22);%0A
       System

Add another soltion with 2 pointers