代码随想录 链表 test 6
面试题 02.07. 链表相交 - 力扣(LeetCode)
如果两个链表相交,则它们从交点开始到结束共用结点,因此如果两个链表长度不一样,且存在差值len,那么这个差值一定是在交点前产生的,因此如果让指向表长的指针先移动len,再同步移动,如果有交点就会同时到达。
/**
* 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* cura = headA;
ListNode* curb = headB;
int sizea = 0, sizeb = 0;
while(cura){
sizea++;
cura = cura->next;
}
while(curb){
sizeb++;
curb = curb->next;
}
cura = headA;
curb = headB;
if (sizeb > sizea) {//找到较长的链表,将cura指向较长链表
swap (sizea, sizeb);
swap (cura, curb);
}
int len = sizea - sizeb;
while(len--){
cura = cura->next;
}
while(cura){
if(cura == curb){
return cura;
}
cura = cura->next;
curb = curb->next;
}
return NULL;
}
};