栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

剑指offer-刷题笔记-简单题-JZ52 两个链表的第一个公共结点

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

剑指offer-刷题笔记-简单题-JZ52 两个链表的第一个公共结点

剑指offer-刷题笔记-简单题-JZ52 两个链表的第一个公共结点 版本1-自己写的,不正确,开始认为不断的删除链表1的节点,直到链表2的长度减少,则删除的节点为公共节点。
class Solution {
public:
    int GetListLength(ListNode* pHead)
    {
        int index = 0;
        while(pHead)
        {
            pHead = pHead->next;
            index++;
        }
        return index;
    }
    
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        //pHead1段节点
        vector< ListNode* > listNodeVec;
        int listLength2  = GetListLength(pHead2);

        if(GetListLength(pHead1) <= 1 || GetListLength(pHead2) <= 1)
        {
            return nullptr;
        }
        //ListNode* pHead = pHead1;
        int count = 0;
        while(pHead1)
        {  
            ListNode* pHead = pHead1;
            pHead1= pHead1->next;
            listNodeVec.push_back(pHead1);
            free(pHead);;  
            if(GetListLength(pHead2) < listLength2)
            {
                //cout<
            //cout<<"ddd"<
            return listNodeVec[0];
        }
        
    }
};
版本2-双指针,因为两个链表非公共部分长度不一致,所以将两个链表链接为一个链表,这样原来的链表就具有同样的长度,可同时进行遍历,即原来 list1,a+b,list2,c+b,之后list1,c+b+a+b,list2,a+b+c+b,
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        ListNode *ta = pHead1, *tb = pHead2;
        while (ta != tb) {
            ta = ta ? ta->next : pHead2;
            tb = tb ? tb->next : pHead1;
        }
        return ta;
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832667.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号