【leetcode】试题 02.02. 返回倒数第 k 个节点

 

/*递归*/
int recursion(struct ListNode* head, int k, int* num){
    if (!head) 
    {
        (*num)=1;
        return 100000;
    }
    int ret = recursion(head->next, k, num);
    if (ret == 100000 && (*num)++ == k) ret=head->val;
    return ret;
}

int kthToLast(struct ListNode* head, int k){
    int num=0;    
    return recursion(head,k,&num);;
}

 

/*快慢指针*/
int kthToLast(struct ListNode* head, int k){
    struct ListNode*t = head;
    while (k--){
        t = t->next;
    }
    while (t){
        t = t->next;
        head = head->next;
    }
    return head->val;
}

 

posted @ 2020-09-23 17:30  温暖了寂寞  阅读(126)  评论(0编辑  收藏  举报