剑指 offer 22. 链表中倒数第k个节点
剑指 Offer 22. 链表中倒数第k个节点
输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。
示例:
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Solution 1
注意边界条件
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) throws IndexOutOfBoundsException {
int index = getListLength(head) - k;
if (index < 0 || k < 0)
throw new IndexOutOfBoundsException();
while (--index >= 0)
head = head.next;
return head;
}
private int getListLength(ListNode head) {
int count = 0;
while (head != null) {
head = head.next;
count++;
}
return count;
}
}
Solution 2
cpp
class Solution
{
public:
ListNode *getKthFromEnd(ListNode *head, int k)
{
int n = -1;
return recursivelyGetKthFromEnd(head, k, n);
}
ListNode *recursivelyGetKthFromEnd(ListNode *head, int k, int &n)
{
if (head == NULL)
{
n = 0;
return NULL;
}
ListNode *result = recursivelyGetKthFromEnd(head->next, k, n);
if (++n == k)
{
return head;
}
return result;
}
};