牛客题霸NC69链表中倒数第k个结点Java题解

牛客题霸NC69链表中倒数第k个结点Java题解

https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=117&&tqId=34991&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

方法:快慢指针
解题思路:利用快慢指针,让快指针former先走k步,然后再让快指针former和慢指针latter一起走,这样当快指针指向链表的末尾为null时,慢指针刚好指向链表的倒数第k个节点。

/*
public class ListNode {
    int val;
    ListNode next = null;
 
    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null || k<=0){
            return null;
        }
 
        ListNode former = head;
        ListNode latter = head;
 
        //former先走n步
        for(int i=0;i<k;i++){
            if(former == null){   //n大于链表长度时
                return null;
            }
            former = former.next;
        }
 
        //former和latter一起走,当former为null时,latter恰好是倒数第k个节点
        while(former!=null){
             former = former.next;
             latter = latter.next;
         }
 
        return latter;
    }
}

 

posted @ 2020-11-26 23:00  云飞扬°  阅读(200)  评论(0编辑  收藏  举报