JZ14-链表中倒数第k个结点
链表中倒数第k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
/**
* 快慢指针 快指针比慢指针先走K步,然后再同时走,则快指针到尾部时,慢指针到达倒数k位
*/
public static ListNode FindKthToTail2(ListNode head,int k) {
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
//先走k步
for (int i = 0; i < k; i++) {
if (fast != null) {
fast = fast.next;
} else {
return null; //如果链表长度还没到k 必须再else中
}
}
//同时走
while (fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
/**
* 找到并删除
*/
public static ListNode FindKthToTail3(ListNode head,int k) {
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
for (int i = 0; i < k; i++) {
if (fast != null) {
fast = fast.next;
} else {
return null; //如果链表长度还没到k 必须再else中
}
}
ListNode pCut = slow;
while (fast != null) {
pCut = slow; //记录slow的上一个,因为slow要被删掉
slow = slow.next;
fast = fast.next;
}
pCut.next = slow.next; //删除slow所在节点
return head;
} 
腾讯成长空间 5958人发布