题目:见下图
答案:见下图
typedef struct ListNode ListNode;
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* getIntersectionNode(struct ListNode* headA, struct ListNode* headB) {
//找长度
ListNode* curA = headA;
int longA=0;
while (curA)
{
longA++;
curA = curA->next;
}
ListNode* curB = headB;
int longB = 0;
while (curB)
{
longB++;
curB = curB->next;
}
//找大值
ListNode* LongList = headA;
ListNode* ShortList = headB;
if (longB > longA)
{
LongList = headB;
ShortList = headA;
}
//走间距
int gap = abs(longA - longB);
while (gap--)
{
LongList = LongList->next;
}
//比较地址
while (LongList)
{
if (LongList == ShortList)
{
return LongList;
}
LongList = LongList->next;
ShortList = ShortList->next;
}
return NULL;
}
解析:
链表是否相交可以使用链表中地址是否相等来进行判断,当两链表地址相同时它们的下一地址指向同一地址或者NULL;
补充:c语言中求两数相减的绝对值的函数是 abs()
(1)求出headA,headB链表的长度longA,longB
ListNode* curA = headA; int longA=0; while (curA) { longA++; curA = curA->next; } ListNode* curB = headB; int longB = 0; while (curB) { longB++; curB = curB->next; }
(2)找出两链表谁大
ListNode* LongList = headA;
ListNode* ShortList = headB;
if (longB > longA)
{
LongList = headB;
ShortList = headA;
}
(3)求两链表长度差值并且使长的链表走差值步使两链表长度相等
原理:
1.链表是否相交可以使用链表中地址是否相等来进行判断,当两链表地址相同时它们的下一地址指向同一地址或者NULL;
2.当headA和headB长度相等时使它们同时往后走当地址相同时,它们即为相同链表
int gap = abs(longA - longB);
while (gap--)
{
LongList = LongList->next;
}
(4)比较两链表地址是否相同并返回
链表是否相交可以使用链表中地址是否相等来进行判断,当两链表地址相同时它们的下一地址指向同一地址或者NULL;
while (LongList)
{
if (LongList == ShortList)
{
return LongList;
}
LongList = LongList->next;
ShortList = ShortList->next;
}
return NULL;
到这里我们解题完毕
如果对您有帮助的话点一个免费的赞和收藏叭!