题目链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/返回两个链表交点的指针。
此题题目中给的输入样例并不是很清楚,实际上只输入了两只头指针。
思路:
判断两个链表长度,然后求差=times.
让指向较长链表的指针先走times步,然后两个指针同时向前走,当指向的地址相同的时候返回。
典型的代码块:
1.判断链表长度:
while (a){
a = a->next;
len_A++;
}
2.让指针向前走time次
while(times){
times--;
a = a->next;
}
最终代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *a = headA;
struct ListNode *b = headB;
int len_A=0,len_B=0,times;
while (a){
a = a->next;
len_A++;
}
while (b){
b = b->next;
len_B++;
}
a = headA;
b = headB;
if (len_A-len_B>0){
times = len_A-len_B;
while(times){
times--;
a = a->next;
}
}
if (len_A-len_B<0){
times = len_B-len_A;
while(times){
times--;
b = b->next;
}
}
while(a && b){
if(a==b) return a;
else{
a = a->next;
b = b->next;
}
}
return NULL;
}