Solution 13: 链表的倒数第K个节点
问题描述
输入一个单向链表,输出该链表中倒数第K个节点,定义倒数第1个节点为链表的尾节点。
如果K值超过链表长度,那么抛出异常。
解决思路
双指针法。
程序
public class LastKthNodeOfList {
public ListNode getLastKthNodeOfList(ListNode head, int k) throws Exception {
if (k <= 0 || head == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && k > 1) {
fast = fast.next;
--k;
}
if (fast == null) {
throw new Exception("Error: k is out of range");
}
while (fast.next != null && slow.next != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}

浙公网安备 33010602011771号