题解 | #链表中倒数最后k个结点#

链表中倒数最后k个结点

https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9

//通过遍历求出链表的长度,然后再减去k来求得目标节点的位序

struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) {

    // write code here

    if(pHead==NULL)

    {

        return pHead;

    }

    struct ListNode* cur=pHead;

    int leng=0,num=0;

    while(cur)

    {

        cur=cur->next;

        leng++;

    }

    if(k>leng)

    {

        return NULL;

    }

    num=leng-k;

    cur=pHead;

    while(num--)

    {

        cur=cur->next;

    }

    return cur;

}

全部评论

相关推荐

notbeentak...:就抓,嗯抓,开不开匿名都要抓,一点坏事不让说,就对公司顶礼膜拜佩服的五体投地就对了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务