Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
null
.
我的AC(32ms,落后2%的人):
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { if (!headA ||!headB) return NULL; struct ListNode *listA = headA; struct ListNode *listB = headB; struct ListNode *longerOne, *shorterOne; int lenA = 0, lenB = 0, sub; while(listA){ lenA++; listA = listA->next; } while(listB){ lenB++; listB = listB->next; } if (lenA > lenB){ sub = lenA - lenB; longerOne = headA; shorterOne = headB; } else{ sub = lenB - lenA; longerOne = headB; shorterOne = headA; } while(sub--){ longerOne = longerOne->next; } while(longerOne){ if (longerOne == shorterOne){ return longerOne; } longerOne = longerOne->next; shorterOne = shorterOne->next; } return NULL; }
分别遍历AB,计算出各自长度lenA,lenB。
然后再遍历,让长的链表从第(长len-短len)个节点开始,短的就从其head开始,当两个节点相同时,即为所求。没遇到说明没相交。
找环入口法(40ms): Leetcode ☞ 142. Linked List Cycle II ☆
把A的尾连在B的头!【A尾连在A头,无意义】弄完记得还原!
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { if (!headA || !headB) return NULL; struct ListNode *tailA = headA; while(tailA->next){ tailA = tailA->next; } tailA->next = headB; //!!!!!!不能连到headA上!连到headA无意义!!!如果AB确实相交,那么就会成为一个环,否则,就成了一个新的长链表而已。 struct ListNode *fast, *slow; fast = slow = headA;//链表A找环入口 while(fast && fast->next){ fast = fast->next->next; slow = slow->next; if (fast == slow) break; } if(!fast || !fast->next){ tailA->next = NULL; return NULL; } fast = headA; while(fast != slow){ fast = fast->next; slow = slow->next; } tailA->next = NULL; return fast; }