22. 链表中倒数第k个节点
小于 1 分钟
22. 链表中倒数第k个节点
参考链接
个人尝试
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode trainingPlan(ListNode head, int cnt) {
        if (head == null) return null;
        //求链表长度
        int len = 0;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            len++;
        }
        //倒数第一个 == 下标为 len - 1
        cur = head;
        int num = 0;
        int delta = len - cnt;
        while(num < delta) {
            cur = cur.next;
            num++;
        }
        return cur;
    }
}优秀题解
class Solution {
    public ListNode trainingPlan(ListNode head, int cnt) {
        ListNode former = head, latter = head;
        for(int i = 0; i < cnt; i++) {
            if(former == null) return null;
            former = former.next;
        }
        while(former != null) {
            former = former.next;
            latter = latter.next;
        }
        return latter;
    }
}
作者:Krahets
链接:https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/solutions/117507/mian-shi-ti-22-lian-biao-zhong-dao-shu-di-kge-j-11/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。