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

链表中倒数最后k个结点

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* FindKthToTail(ListNode* pHead, int k) {
        // write code here        
        //空链表检测
        int listLength = 0;
        if(pHead != nullptr)
            listLength++;
        else
            return nullptr;
        
        //计算链表长度
        auto head = pHead;
        auto current = head;
        while (current->next != nullptr) {
            current = head->next;
            head = current;
            listLength++;
        }
        //链表长度小于k
        if(k > listLength)
            return nullptr;
        //返回该链表中倒数第k个节点
        int index = 0;
        head = pHead;
        current = head;
        while (index++ < listLength-k) {
            current = head->next;
            head = current;
        }
        return head;
    }

};

#链表中倒数K个结点##链表#
全部评论

相关推荐

鼠鼠没有找到暑期实习,简历太空了,感觉直接去秋招会完蛋,这个时间点找个日常实习混个简历,边实习边准备秋招有没有搞头啊
梦想是成为七海千秋:可以的完全可以的,找不到暑期就找日常,秋招之前还是有很多时间可以实习的,哪怕只实习了一个月都可以写在简历上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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