[LeetCode] 160. Intersection of Two Linked Lists 解题思路
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:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
问题:判断两个列表是否有相交的元素,若有,找出相交节点。
这题也是一道基础题,看了自己的列表知识还需要巩固下才好。
分别求出两个列表的长度 len1, len2 ,以及他们的长度差异 diff
跳过长度差异部分,对于剩余的相同长度部分,依次检查两个链表的对应节点,若又存在相交节点,则必有两个对应节点相等。
1 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 2 3 int len1 = 0; 4 ListNode* p1 = headA; 5 while(p1 != NULL){ 6 p1 = p1->next; 7 len1++; 8 } 9 10 int len2 = 0; 11 ListNode* p2 = headB; 12 while(p2 != NULL){ 13 p2 = p2->next; 14 len2++; 15 } 16 17 p1 = headA; 18 p2 = headB; 19 if (len1 > len2){ 20 int diff = len1 - len2; 21 while(diff > 0){ 22 p1 = p1->next; 23 diff--; 24 } 25 } 26 27 if (len2 > len1){ 28 int diff = len2 - len1; 29 while(diff > 0){ 30 p2 = p2->next; 31 diff--; 32 } 33 } 34 35 while(p1 != NULL ){ 36 if ( p1 == p2){ 37 return p1; 38 } 39 p1 = p1->next; 40 p2 = p2->next; 41 } 42 43 return NULL; 44 }
参考资料:
LeetCode: Intersection of Two Linked Lists 解题报告, Yu's garden