Skip to content

剑指offer22 FindKthNodeToTail.java #3

Description

@dayAndnight2018

对于前面的指针先走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;
}`

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions