题目描述
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null
eg
题解
先求出两个链表的长度,然后让较长链表的指针先走n步(n为两链表的长度差),然后两链表指针同步移动,若有重合则求出交点,都走到末尾还没有找到就返回null
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* dummyA=new ListNode(0);
ListNode* dummyB=new ListNode(0);
dummyA->next=headA;
dummyB->next=headB;
int sizeA=0, sizeB=0;
ListNode *currA=dummyA;
ListNode *currB=dummyB;
while(currA->next!=nullptr)
{
currA=currA->next;
sizeA++;
}
while(currB->next!=nullptr)
{
currB=currB->next;
sizeB++;
}
if(sizeA>sizeB)
{
currA=dummyA;
currB=dummyB;
for(int i=0;i<(sizeA-sizeB);i++)
currA=currA->next;
while(currA->next!=nullptr&&currB->next!=nullptr)
{
currA=currA->next;
currB=currB->next;
if(currA==currB)
return currA;
}
return nullptr;
}
else
{
currA=dummyA;
currB=dummyB;
for(int i=0;i<(sizeB-sizeA);i++)
currB=currB->next;
while(currA->next!=nullptr&&currB->next!=nullptr)
{
currA=currA->next;
currB=currB->next;
if(currA==currB)
return currA;
}
return nullptr;
}
}
};