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

链表中倒数最后k个结点

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

1.翻转链表去做,然后按照这个顺序找第k-1个数,然后在与原来的链表进行对比
2.这里要考虑到深拷贝和浅拷贝的问题,同时还要考虑到k为零的情况
3.做法比较复杂
/**
 * 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* reverseList(ListNode* L1)
    {
        if(L1 == nullptr) return nullptr;
        //ListNode* newList;
        //链表原地翻转时会连着以前的链表一起翻转
        ListNode* pre = nullptr;
        ListNode* cur = L1;
        //cur->next = nullptr;
        while(cur != nullptr)
        {
            //以cur作为中间中转点
            ListNode* next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        
        return pre;
    }
    ListNode* FindKthToTail(ListNode* pHead, int k) {
        // write code here
        //翻转链表,然后再迭代k次,采用原地翻转的形式
        if(k == 0 )
        {
            return {};
        }
        if(pHead == nullptr) return nullptr;
        //ListNode* newList,这里涉及到深拷贝和浅拷贝的问题
        ListNode* cpHead = new ListNode(-1);
        cpHead = pHead;
        //做一个深拷贝,防止翻转的时候出现问题
        ListNode* deepCopy = new ListNode(-1);
        ListNode* go = deepCopy;
        while(cpHead != nullptr)
        {
            ListNode* temp = new ListNode(cpHead->val);
            go->next = temp;
            go = go->next;
            cpHead = cpHead->next;
        }
        deepCopy = deepCopy->next;
        //深拷贝已构造完毕
        cpHead = pHead;
        ListNode* pre = reverseList(cpHead);
        cpHead = deepCopy;

        for(int i = 0; i < k - 1; i++)
        {
            pre = pre->next;
            if(pre == nullptr) return {};
        }
        //找到与原拷贝节点相同的位置开始
        while(pre->val != deepCopy->val)
        {
            deepCopy = deepCopy->next;
            if(deepCopy == nullptr) return {};
        }
        return deepCopy;
    }
};

全部评论

相关推荐

哥_留个offer先:跟他说,你这个最好用c#,微软就用c#Java不适合这个项目
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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