剑指offer之 两个链表的第一个公共节点

题目描述

输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)

思路

  1. 首先确定两个链表的长度,然后移动长链表的指针至共同长度处后开始遍历
  2. 思路类似,不过不需要求链长,目的还是使得两个链表从共同长度处开始遍历

代码

方法1:

class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if (pHead1 == NULL || pHead2 == NULL)
            return NULL;
        
        ListNode* List1 = pHead1;
        ListNode* List2 = pHead2;
        int List1_Length = 0;
        int List2_Length = 0;
        int count = 0;
        while(List1 != NULL)
        {
            List1 = List1->next;
            List1_Length++;
        }
        while(List2 != NULL)
        {
            List2 = List2->next;
            List2_Length++;
        }
        if (List1_Length > List2_Length)
        {
            
            while (count < List1_Length - List2_Length)
            {
                pHead1 = pHead1->next;
                count++;
            }
        }
        else if (List1_Length < List2_Length)
        {
            while (count < List2_Length - List1_Length)
            {
                pHead2 = pHead2->next;
                count++;
            }
        }
        
        while (pHead1 != pHead2 && pHead1 != NULL && pHead2 !=NULL)
        {
            pHead1 = pHead1->next;
            pHead2 = pHead2->next;
        }
        
        return pHead1;
    }
};

方法2:

class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if (pHead1 == NULL || pHead2 == NULL)
            return NULL;
        
        ListNode* List1 = pHead1;
        ListNode* List2 = pHead2;
        
        while (List1 != List2)
        {
            if (List1 == NULL)
                List1 = pHead2;
            else
                List1 = List1->next;
            
            if (List2 == NULL)
                List2 = pHead1;
            else
                List2 = List2->next;
        }
        return List1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值