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
思路:1. 记录两个list的长度,并检测最后一个元素是否相同。如果不同,表明No intersection。 2. 计算list的长度差offset,让长的list的指针先移动offset,然后两个list的指针一起移动,第一个相同的element就是所求node
2.第二种方法,也很diao! 代码十分简洁
链接 https://leetcode.com/discuss/17278/accepted-shortest-explaining-algorithm-comments-improvements
3.第二种是先计算listB中value的总和,再将listA中的所有value增加m,再次计算listB中value总和,如果相同no intersection,不同就有!方法仅仅局限于integer
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(!headA || !headB) return NULL; if(headA==headB) return headA; ListNode *pa=headA; ListNode *pb=headB; int la=1; int lb=1; while(pa && pa->next) {pa=pa->next;la++;} while(pb && pb->next) {pb=pb->next;lb++;} if(pa!=pb) return NULL; int offset = abs(la-lb); pa=headA; pb=headB; while(offset>0){ if(la>lb) pa=pa->next; else pb=pb->next; offset--; } while(pa && pb){ if(pa==pb) return pa; pa=pa->next; pb=pb->next; } } };
turnsoul