【剑指offer】面试题52. 两个链表的第一个公共节点

2020.8.18更新

#include<iostream>
using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
 
class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
        int Len1 = getListLength(headA);//计算长度
        int Len2 = getListLength(headB);
        int dif = Len1 - Len2;
        ListNode* pListLong = headA;
        ListNode* pListShort = headB;
        if (Len1 < Len2) {//len1<len2时,交换
            swap(pListLong, pListShort);
            dif = Len2 - Len1;
        }
        for (int i = 0; i < dif; i++) {
            pListLong = pListLong->next;
        }
        while (pListLong != nullptr && pListShort != nullptr && pListLong != pListShort) {//long不为空,short不为空,两者不等
            pListLong = pListLong->next;
            pListShort = pListShort->next;
        }
        return pListLong;
    }
    int getListLength(ListNode* list) {//获取长度
        unsigned int nLength = 0;
        ListNode* pNode = list;
        while (pNode != nullptr) {
            nLength++;
            pNode = pNode->next;
        }
        return nLength;
    }
};

解题思路

采用两个指针,快指针指向长链表,慢指针指向短链表,先求出两者的长度,再求出长链表比短链表的差值diff,之后让快指针先走diff步后,再和慢指针一起走,直到达到边界条件为止

时间复杂度

o(m+n),m和n分别为两个链表的长度

代码

class Solution {
public:
	ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
		ListNode* l1 = headA, * l2 = headB;
		//求l1的长度
		int countL1 = 0;
		while (l1 != nullptr)
		{
			countL1++;
			l1 = l1->next;
		}
		//求l2的长度
		int countL2 = 0;
		while (l2 != nullptr)
		{
			countL2++;
			l2 = l2->next;
		}
		//求l1和l2的差值,l1指向长链表,l2指向短链表
		l1 = headA;
		l2 = headB;
		int diff = countL1 - countL2;
		//判断两者谁更长
		if (countL1 < countL2)
		{
			l1 = headB;
			l2 = headA;
			diff = countL2 - countL1;
		}
		//l1先走diff步
		while (diff--)
		{
			l1 = l1->next;
		}
		//找共同节点
		while (l1 != nullptr && l2 != nullptr && l1 != l2)
		{
			l1 = l1->next;
			l2 = l2->next;
		}
		return l1;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值