LeetCode

Intersection of Two Linked Lists

2015.1.23 12:53

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.

Solution:

  The problem description especially required the code to run in O(n) time and O(1) space. Thus I came up with the most direct way.

  Just count the lengths of both lists, set two pointers from the list heads, align them to equipotential position and move'em forward until they coincide.

  That would be the answer we seek.

  Time complexity should be O(n + m), if you name the lengths of both lists to be "n" and "m". Extra space required is O(1).

Accepted code:

 1 // 1AC, count the number of nodes and align them
 2 /**
 3  * Definition for singly-linked list.
 4  * struct ListNode {
 5  *     int val;
 6  *     ListNode *next;
 7  *     ListNode(int x) : val(x), next(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
13         ListNode *p1, *p2;
14         int n1, n2;
15         
16         p1 = headA;
17         n1 = 0;
18         while (p1 != nullptr) {
19             ++n1;
20             p1 = p1->next;
21         }
22         
23         p2 = headB;
24         n2 = 0;
25         while (p2 != nullptr) {
26             ++n2;
27             p2 = p2->next;
28         }
29         
30         p1 = headA;
31         p2 = headB;
32         
33         int i;
34         if (n1 < n2) {
35             for (i = 0; i < n2 - n1; ++i) {
36                 p2 = p2->next;
37             }
38         } else if (n1 > n2) {
39             for (i = 0; i < n1 - n2; ++i) {
40                 p1 = p1->next;
41             }
42         }
43         
44         while (p1 != nullptr && p2 != nullptr && p1 != p2) {
45             p1 = p1->next;
46             p2 = p2->next;
47         }
48         
49         return p1;
50     }
51 };
原文地址:https://www.cnblogs.com/zhuli19901106/p/4243987.html