编写一个程序,找到两个单链表相交的起始节点。
例如,下面的两个链表:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
在节点 c1 开始相交。
注意:
- 如果两个链表没有交点,返回
null
. - 在返回结果后,两个链表仍须保持原有的结构。
- 可假定整个链表结构中没有循环。
- 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
解法:可以算出a链,b链的长度,以及是否有相交部分(最后一个节点是否相同即可),知道了长度i,j,如果i=j,那么我们两个指针从头同时出发,一定会同时相等于相交点,如果i>j,那么a链指针pt1先走上i-j步,再和pt2同时走,j>i同理。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==NULL||headB==NULL)return NULL;
ListNode*pt1=headA;
ListNode*pt2=headB;
int i=0;
int j=0;
while(pt1->next!=NULL){
pt1=pt1->next;
++i;
}
while(pt2->next!=NULL){
pt2=pt2->next;
++j;
}
if(pt2!=pt1)return NULL;
pt1=headA;
pt2=headB;
if(i==j){
while(pt1!=pt2){
pt1=pt1->next;
pt2=pt2->next;
}
return pt1;
}
else if(i>j){
for(int c=0;c<i-j;c++){
pt1=pt1->next;
}
while(pt1!=pt2){
pt1=pt1->next;
pt2=pt2->next;
}
return pt1;
}
else{
for(int c=0;c<j-i;c++){
pt2=pt2->next;
}
while(pt1!=pt2){
pt1=pt1->next;
pt2=pt2->next;
}
return pt1;
}
}
};