public class 链表中倒数第k个节点_04 {
public ListNode FindKthToTail(ListNode head, int k) {
//判断链表是否为空
if (head == null)
return head;
//判断k是否为0
if (k == 0)
return null;
//使用快慢指针法辅助寻找倒数第k个节点
//快慢指针均指向头结点,快指针向后移动k-1个节点,慢指针不动
ListNode fast = head;
ListNode slow = head;
int i = 0;
while (++i < k) {
fast = fast.next;
if (fast == null)
return null;
}
//当快指针走到链表尾节点时,慢指针刚好指导链表倒数第k个节点
while (fast.next != null && slow.next != null) {
fast = fast.next;
slow = slow.next;
}
//如果慢指针为空的话,返回空
//否则返回慢指针,即倒数第k个节点
if (slow == null)
return null;
else
return slow;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
}
链表中倒数第k个节点
最新推荐文章于 2023-02-22 19:45:18 发布