简体   繁体   English

破解编码访谈链接列表Q2

[英]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. 在讨论链接列表主题时,我陷入了问题2。我能够提出一个非递归版本,并且工作正常。 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. 因此,在这段代码中,我相信代码的int i = nthToLast(head.next,k)+1行可以确保头指针指向最后一个节点。 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? 谁能帮助我理解这一行代码,以及如何将指针从链表的第一个节点更改为最后一个节点?

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. 该函数将自身传递给下一个头部,直到最后一个头部将为null,从而返回零,因此您有很多函数调用,具体取决于最后一个null头部以求值为零。 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 一旦到达最后一个头,我就可以评估为0 + 1,然后打印i和K,将i(现在为1)传递给挂起的函数调用,成为1 + 1,然后打印新的i + k和以此类推,直到到达初始指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM