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.

 

Runtime: 52ms. 

 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         if(!headA && !headB) return NULL;
13         if(!headA || !headB) return NULL;
14         
15         // compute the length of A and B
16         ListNode* moveA = headA;
17         int lengthA = 1;
18         while(moveA->next) {
19             moveA = moveA->next;
20             lengthA++;
21         }
22         
23         ListNode* moveB = headB;
24         int lengthB = 1;
25         while(moveB->next) {
26             moveB = moveB->next;
27             lengthB++;
28         }
29         
30         if(moveA->val != moveB->val) return NULL;
31         
32         // ensure A B are of same length
33         moveA = headA;
34         moveB = headB;
35         while(lengthA > lengthB) {
36             moveA = moveA->next;
37             lengthA--;
38         }
39         while(lengthB > lengthA) {
40             moveB = moveB->next;
41             lengthB--;
42         }
43         
44         // get the intersection
45         ListNode* result = moveA;
46         while(moveB) {
47             if(moveA->val != moveB->val)
48                 result = moveA->next;
49             moveA = moveA->next;
50             moveB = moveB->next;
51         }
52         return result;
53     }
54 };

 

Analyse: A:  --------x------

              -------c-----

        B: -----y-------

x + c + y = y + c + x

Runtime: 52ms. 

 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* moveA = headA, *moveB = headB;
13         
14         while(moveA != moveB) {
15             moveA = moveA ? moveA->next : headB;
16             moveB = moveB ? moveB->next : headA;
17         }
18         return moveA;
19     }
20 };

 

posted @ 2016-08-06 04:20  amazingzoe  阅读(130)  评论(0编辑  收藏  举报