algorithm icon indicating copy to clipboard operation
algorithm copied to clipboard

剑指offer22 FindKthNodeToTail.java

Open dayAndnight2018 opened this issue 6 years ago • 0 comments

对于前面的指针先走K步的做法欠妥,当k大于长度的时候,将会出现空指针异常。 for (int i = 0; i < k-1; i++) { before = before.next; } // 2. n < k: 第k个元素before已经到null,则k > n if (before == null) return null;

建议:

`int length = k;

    //先让前面的指针走K步,然后在一起走,前面的指针走到最后,后面的指针指向倒数第K个节点
    while(length > 1 && node2 != null)
    {
        node2 = node2.next;
        length--;
    }
            
    if(length > 1 || node2 == null)
    {
        return null;
    }`

dayAndnight2018 avatar Jul 27 '19 08:07 dayAndnight2018