160 intersection_of_Two_Linked_Lists
难度: Easy
刷题内容
原题连接 * https://leetcode-cn.com/problems/intersection-of-two-linked-lists/ 内容描述
Write a program to find the node at which the intersection of two singly linked lists begins.
解题方案
思路 1
1. 求长度差
2. 长的链表先走掉长的部分
3. 一起走,相遇即为交点
ListNode *getIntersectionNode(ListNode * headA, ListNode * headB) {
int lena=0;
int lenb=0;
ListNode *a = headA;
ListNode *b = headB;
while(a){
lena++;
a=a->next;
}
while(b){
lenb++;
b=b->next;
}
if(a!=b)
return NULL;
int sub=abs(lena-lenb);
if(lena>lenb){
while(sub--)
headA=headA->next;
}else
while(sub--)
headB=headB->next;
while(headA!=headB){
headA = headA->next;
headB = headB->next;
}
return headA;
}