单向链表中倒数第 k 个节点。返回该节点的值。

实现一种算法,找出单向链表中倒数第 k 个节点。返回该节点的值。

一、思路

1、先统计总共的结点数 tot
2、然后再遍历到第 tot + 1 - k 个就是倒数第 k 个了

二、源码

int listCount(struct ListNode *l) {
    int cnt = 0;
    while(l) {
        ++cnt;
        l = l->next;
    }
    return cnt;
}

int kthToLast(struct ListNode* head, int k){
    int tot = listCount(head);
    int cnt = 0;
    while(head) {
        if(++cnt == tot + 1 - k) {
            return head->val;
        }
        head = head->next;
    }
    return 0;
}