跟删除链表中倒数第n个结点做法一样,用快慢指针,只是本题需要加多一个判断,当快指针先走完的时候,证明倒数第k个结点已经超出了链表的头结点,此时直接返回null
public class Solution { public ListNode FindKthToTail(ListNode head,int k) { if(head == null) return head; ListNode pre = new ListNode(0); pre.next = head; ListNode start = pre; ListNode end = pre; while(k != 0){ start = start.next; if(start == null) return null; k--; } while(start.next != null){ start = start.next; end = end.next; } return end.next; } }