目录
一、题目
题目链接:160. 相交链表 - 力扣(LeetCode) (leetcode-cn.com)
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null
二、解题思路
首先需要判断两链表是否是相交的,即两链表的最后一个结点是否相同。
struct ListNode* curA = headA;
struct ListNode* curB = headB;
int lenA = 1;
int lenB = 1;
// 遍历记录长度
while (curA->next)
{
curA = curA->next;
lenA++;
}
while (curB->next)
{
curB = curB->next;
lenB++;
}
// 判断是否相交
if (curA != curB)
{
return NULL;
}
让长的链表走K步,K是长链表比短链表多的长度
然后两链表同时进行遍历
curA = headA;
curB = headB;
struct ListNode* longList = curA;
struct ListNode* shortList = curB;
if (lenA < lenB)
{
longList = curB;
shortList = curA;
}
int k = abs(lenA - lenB);
while (k--)
{
longList = longList->next;
}
// 遍历找相交节点
while (longList != shortList)
{
longList = longList->next;
shortList = shortList->next;
}
struct ListNode* Node = longList;
return Node;
三、代码实现
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode* curA = headA;
struct ListNode* curB = headB;
int lenA = 1;
int lenB = 1;
// 遍历获得两链表的长度
while (curA->next)
{
curA = curA->next;
lenA++;
}
while (curB->next)
{
curB = curB->next;
lenB++;
}
// 判断两链表是否相交
if (curA != curB)
{
return NULL;
}
curA = headA;
curB = headB;
struct ListNode* longList = curA;
struct ListNode* shortList = curB;
// 区分长短链表
if (lenA < lenB)
{
longList = curB;
shortList = curA;
}
int k = abs(lenA - lenB);
// 长链表先走K步
while (k--)
{
longList = longList->next;
}
// 同时遍历找相交节点
while (longList != shortList)
{
longList = longList->next;
shortList = shortList->next;
}
struct ListNode* Node = longList;
return Node;
}