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 - 1) {
        return current.data;
      }
      i++;
      current = current.next;
    }

    return -1;
  }

  private int findElement2(CustomLinkedList<Integer> list, int k) {
    Node<Integer> current = list.head();
    Node<Integer> runner = current;

    for (int i = 0; i < k + 1; i++) {
      runner = runner.next;
    }

    while (runner != null) {
      current = current.next;
      runner = runner.next;
    }

    return current.data;
  }

  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.print("Element at k from last - Method 2: " + kthToLast.findElement2(list, k) + "\n");
      System.out.println();
    }

    scanner.close();
  }
}

@@ -278,16 +278,192 @@
 Last %7B%0A%0A
+  /**%0A   * Finds element at Kth position from the last element using the index%0A   * %0A   * Complexity: O(n)%0A   * %0A   * @param list%0A   * @param k%0A   * @return foundElement%0A   */%0A
   privat
@@ -578,16 +578,84 @@
 i = 0;%0A%0A
+    // return element if the index is at k distance from the size-1%0A
     whil
@@ -819,16 +819,182 @@
 1;%0A  %7D%0A%0A
+  /**%0A   * Finds element at Kth position from the last element using two pointers%0A   * %0A   * Complexity: O(n)%0A   * %0A   * @param list%0A   * @param k%0A   * @return%0A   */%0A
   privat
@@ -1131,16 +1131,74 @@
 rrent;%0A%0A
+    // move the fast pointer k positions from the current%0A
     for 
@@ -1258,24 +1258,134 @@
 ext;%0A    %7D%0A%0A
+    /*%0A     * when the runner reaches the end the current would be at k distances from%0A     * the end%0A     */%0A
     while (r

Question 2.2 complete