Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

剑指offer22 FindKthNodeToTail.java #3

Open
dayAndnight2018 opened this issue Jul 27, 2019 · 0 comments
Open

剑指offer22 FindKthNodeToTail.java #3

dayAndnight2018 opened this issue Jul 27, 2019 · 0 comments

Comments

@dayAndnight2018
Copy link

对于前面的指针先走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;
    }`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant