题目链接

牛客网

题目描述

输入一个链表,输出该链表中倒数第k个结点。

解题思路

快慢指针,相隔k个ListNode,fast==null时,返回slow

public class Solution {
   
    public ListNode FindKthToTail(ListNode head,int k) {
   
    ListNode slow = head, fast = slow;
        for (int i=0;i<k;i++) {
   
            if (fast==null) return null;
            fast = fast.next;
        }
        while (fast != null) {
   
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}