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

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

版本1-自己写的,不正确,开始认为不断的删除链表1的节点,直到链表2的长度减少,则删除的节点为公共节点。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
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<<GetListLength(pHead2)<<endl;
                break;
            }
            count ++;
              
        }
        cout<<listNodeVec.size()<<endl;
        if(count == 0)
        {
            //cout<<"ddd"<<endl;
            return listNodeVec[0];
        }else{
            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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值