class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(!headA | !headB) return nullptr;
ListNode* A = headA;
ListNode* B = headB;
int lengthA = 0;
int lengthB = 0;
while(A){ //获取链表A长度
A = A -> next;
lengthA ++;
}
while(B){ //获取链表B长度
B = B -> next;
lengthB ++;
}
if(A == B){ //尾结点相等,表示两个链表必相交
if(lengthA > lengthB){ //此时定义快慢指针,用A表示快指针,B表示慢指针
A = headA;
B = headB;
int tmp = lengthA - lengthB;
while(A){
A = A -> next;
if(tmp <= 0) B = B -> next; //利用长度差走到相同节点
tmp --;
if(A == B) return A;
}
}else{
A = headB;
B = headA;
int tmp = lengthB - lengthA;
while(A){
if(A == B) return A;
A = A -> next;
if(tmp <= 0) B = B -> next;
tmp --;
}
}
}
return nullptr;
}
};
<Talk is cheap, show me the code 38> 链表相交
于 2024-07-16 17:18:05 首次发布