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.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
求两个链表的第一个公共结点
思路一:遍历得到两个链表的长度,求出他们之差,用的长的链表先走若干步,接着在同时在两个链表上遍历,找到的第一个相同的结点就是他们的共同的结点
思路二:如果短链遍历完了还没有得到结果,则将指针指向长链头,长链头遍历完了之后指向短链头,这样来消除他们长度差异
C++(64ms):
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 int getListLen(ListNode* head){ 12 int len = 0 ; 13 ListNode* p = head ; 14 while(p != NULL){ 15 len++ ; 16 p = p->next ; 17 } 18 return len ; 19 } 20 21 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 22 int len1 = getListLen(headA); 23 int len2 = getListLen(headB); 24 int lenDif = len1 - len2 ; 25 ListNode* pLong = headA ; 26 ListNode* pShort = headB ; 27 if (len2 > len1){ 28 lenDif = len2 - len1 ; 29 pLong = headB ; 30 pShort = headA ; 31 } 32 while(lenDif--){ 33 pLong = pLong->next ; 34 } 35 while(pLong != pShort && pLong != NULL && pShort != NULL){ 36 pLong = pLong->next ; 37 pShort = pShort->next ; 38 } 39 return pLong ; 40 } 41 };
C++(37ms):
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 12 ListNode* p1 = headA ; 13 ListNode* p2 = headB ; 14 if (p1 == NULL || p2 == NULL) 15 return NULL ; 16 while(p1 != NULL && p2 != NULL && p1 != p2){ 17 p1 = p1->next ; 18 p2 = p2->next ; 19 20 if (p1 == p2) 21 return p1 ; 22 if (p1 == NULL) 23 p1 = headB ; 24 if (p2 == NULL) 25 p2 = headA ; 26 } 27 return p1 ; 28 } 29 };