160. 相交链表 - 力扣(LeetCode)
目录
官方双指针解法:
博主的辣眼代码:
每日一表情包:
博主还未学习哈希表,所以介绍的是双指针法,此题的哈希表解法时O(n+m)空O(m)
而今天的这个双指针的解法时O(n+m)O(1) ,绝对值得你细细品味,
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台(官方的解释)
我在这里也不好说啥,双指针解法易想,但是这些细节真的很难抓住,让我们来欣赏吧(欣赏前建议自己写写)
官方双指针解法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(headA == NULL || headB == NULL){
return NULL;
}
struct ListNode* pa = headA, *pb = headB;
while(pa != pb){
pa = pa == NULL ? headB : pa->next;
pb = pb == NULL ? headA : pb->next;
}
return pa;
}
博主的辣眼代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
//对齐,切菜,指图示中的a1和b2结点对齐,然后切菜(指比较)
if(headA == NULL || headB ==NULL){
return NULL;
}
int Acount = 1;
int Bcount = 1;
int count = 0;
struct ListNode* pa = headA;
struct ListNode* pb = headB;
//对齐
while(pa){
pa = pa->next;
Acount++;
}
while(pb){
pb = pb->next;
Bcount++;
}
if(Acount > Bcount){
count = Acount - Bcount;
while(count){
headA = headA->next;
count--;
}
}
else{
count = Bcount - Acount;
while(count){
headB = headB->next;
count--;
}
}
//找相交结点
while(headA != headB && headA){
headA = headA->next;
headB = headB->next;
}
if(headA == headB && headA){
return headA;
}
return NULL;
}
每日一表情包:
你的点赞对我很重要!爱你哟!