vamsu
8/18/2018 - 8:59 PM

Practice recursion Kth from last

Practice recursion Kth from last

import java.io.*;
import java.util.*;


// Recursion practice
class Solution {
  class Node {
   int value;
   Node next;
    
   Node(int value, Node next){
     this.value = value;
     this.next = next;
   }
    
   public void print(){
     System.out.print(this.value + ",");
     if(this.next != null) {
       this.next.print();
     }
   }
 
  }
  public static void main(String[] args) {
    Solution solution = new Solution();
    int[][] input = {
      {23,5,15,24,12},
      {1,2,3,4,5},
      {5,3,24,1,121,2}
    };
    
    int[] kth = {2,5,130};
    
    for(int i=0; i< input.length; i++){
      Node root = solution.createList(input[i]);
      System.out.print("Input :");
      root.print();
      System.out.print(" ResultI: " + solution.kthFromLast(root, kth[i]));
      System.out.print(", ResultR: " + solution.kthFromLastR(root, kth[i]));
      System.out.print(", Result2: " + solution.kthFromLastR2(root, kth[i]));
      
      System.out.println();
    }
  }
  
  
  public Node createList(int[] input){
    Node root = null;
    for(int i=input.length-1;i>=0;i--){
      Node newNode = new Node(input[i], root);
      newNode.next = root;
      root = newNode;
    }
    return root;
  }
  
  public int kthFromLast(Node root, int k) {
    if( root == null) return -1;
    Node runner = root;
    for(int i=0;i<k;i++){
      if(runner == null) {
       return -1; 
      }
      runner = runner.next;
    }
    Node current = root;
    while(runner != null) {
      runner = runner.next; 
      current = current.next;
    }
    return current.value;   
  }  
  
  
  public int kthFromLastR(Node root, int k) {
    return kthFromLastR(root, root, k);
  }
  
  private int kthFromLastR(Node head, Node tail, int k){
    if(tail == null) {
      return k >0 ? -1: head.value;
    }
    if(k > 0 ){
      return kthFromLastR(head, tail.next, k-1);
    } else {
      return kthFromLastR(head.next, tail.next, k-1);
    }
  }
  
  public int kthFromLastR2(Node root, int k) {
    return kthFromLastR2(root, k, new int[]{0});
  }
  
  public int kthFromLastR2(Node root, int k, int[] pos) {
    if(root==null) {
      return -1;
    }
    int result = kthFromLastR2(root.next, k, pos);
    pos[0]++;
    if(pos[0]==k){
     result = root.value; 
    }
    return result;
  }
}