user3293890
user3293890

Reputation: 13

Cracking the coding interview Linked List Q2

I was going over the coding interview book. While cover the linked list topic, I was stuck with question 2. I was able to come up with a non-recursive version and that is working properly. However, while I was trying to go over the book solution, I wasnt able to understand the solution. I was wondering if anyone can help me out with that?

public static int nthToLast(SListNode head, int k){
    if(head == null){
        return 0;
    }

    int i = nthToLast(head.next, k) +1;
    System.out.println("Node data is: " + head.item);
    System.out.println("i is: " +i);
    System.out.println("k is: " + k);
    if(i<=k){
        System.out.println(head.item);
    }
    return i;

}

So in this code, I believe that int i = nthToLast(head.next, k) +1 line of the code is making sure that the head pointer points to the last node. But I am not able to understand the mechanism behind the change of pointer from the first node to the last node through this line. Can anyone please help me understand this line of code and how its changing the pointer from first to last node of linkedlist?

Upvotes: 0

Views: 383

Answers (1)

a.atlam
a.atlam

Reputation: 742

this function is passing to itself the next head until at the last head it will be null, thus returning zero, so you have many function calls depending on that last null head to evaluate to zero. As soon as that last head is reached finally i can be evaluated to 0+1 followed by printing i and K, the i (now is 1) is passed to the pending function call becoming 1+1 then printing the new i + k and so on till you reach the initial pointer

Upvotes: 1

Related Questions