题目链接:
https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/description/
思路:两个链表相交,两条链表一定分别存在某个节点,设链表1的这个节点为node1,链表2的这个节点为node2, node1==node2,也就是node1的地址(不是node1指向的地址)与node2的地址(不是node2指向的地址)相同,代表node1和node2是同一个节点,从这个结点之后,两条链表所有结点的地址都对应相同
1.循环遍历List1,List2,得到List1链表的长度为len1,得到List2链表的长度为len2;
2.假如List2的链表长度长,就让List2链表的长度减小,使List1的长度与List2一样长,然后再进行遍历(我的表述可能不准确,可以看一下代码就理解了),如图,让List1,List2都从长度相同的时候开始依次遍历,都从箭头处开始遍历。
/**
* 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) {
int lena=0;
int lenb=0;
ListNode* a=headA;
ListNode* b=headB;
int i=0;
while(a!=NULL){
a=a->next;
lena++;
}
while(b!=NULL){
b=b->next;
lenb++;
}
//重新指向各自的头节点
a=headA;
b=headB;
if(lena>lenb){
int len=lena-lenb;
while(true){
if(i==len){
break;
}
a=a->next;
i++;
}
}
if(lena<lenb){
int len=lenb-lena;
while(true){
if(i==len){
break;
}
b=b->next;
i++;
}
}
while(true){
//当链表只想NULL时,还不存在两个结点地址相等的情况,就代表这不是一个相交链表
if(a==NULL||b==NULL){
return NULL;
}
if(a==b){
return a;
}
a=a->next;
b=b->next;
}
}
};