题目:
力扣链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/submissions/
思路:
结点都是独立的,只是被某个链表,通过某种关系链接起来了。
一旦2个链表相交,那么他们至少最后一个结点一定是相同。
我们通过用例图得到交点
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9xKPNU2z-1636643518883)(相交链表.assets/image-20211109223018684-16364682195492.png)]
代码:
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(headA==NULL||headB==NULL)
{
return NULL;
}
struct ListNode *nodeA=headA ;
int lenA=0;//记录A的结点数
struct ListNode *nodeB=headB;
int lenB=0;//记录B的结点数
while(nodeA->next!=NULL)
{
lenA++;
nodeA=nodeA->next;
}
while(nodeB->next!=NULL)
{
lenB++;
nodeB=nodeB->next;
}
if(nodeA!=nodeB)//判断是否相交,不相等,说明不相交,否则相交
{
return NULL;
}
//创造条件
if(lenA>=lenB)
{
int a=lenA-lenB;
while(a-->0)
{
headA=headA->next;
}
}else
{
int a=lenB-lenA;
while(a-->0)
{
headB=headB->next;
}
}
while(headA!=headB)
{
headA=headA->next;
headB=headB->next;
}
return headA;
}