赶新鲜,和solution的解法不太一样,解三元一次方程组。。。
简而言之,list A的长度是x+z, listB的长度是y+z. z为两个list共同部分的长度。把A reverse一下,可以得到x+y的值,然后算一下就都出来了。
ListNode* reverseList(ListNode* head){
if (!head){
return NULL;
}
if (!head->next){
return head;
}
ListNode* pre = NULL;
ListNode* cur = head;
while (cur->next){
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
cur->next = pre;
return cur;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA || !headB){
return NULL;
}
ListNode* pa = headA;
int countX = 1;
while (pa->next){
pa = pa->next;
countX++;
}
ListNode* pb = headB;
int countY = 1;
while (pb->next){
pb = pb->next;
countY++;
}
if (pa != pb){
return NULL;
}
ListNode* tmp = reverseList(headA);
pb = headB;
int countZ = 0;
while (pb->next){
pb = pb->next;
countZ++;
}
reverseList(tmp);
int a = (countX - countY + countZ) / 2;
pa = headA;
while (a--){
pa = pa->next;
}
return pa;
}