160. Intersection of Two Linked Lists

Posted lvbbg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了160. Intersection of Two Linked Lists相关的知识,希望对你有一定的参考价值。

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.

 

 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 == NULL || headB == NULL)
13             return NULL;
14         
15         int len1 = 1;
16         ListNode *TailA = headA;
17         while(TailA->next != NULL)
18         {
19             TailA = TailA->next;
20             len1++;
21         }
22         
23         int len2 = 1;
24         ListNode *TailB = headB;
25         while(TailB->next != NULL)
26         {
27             TailB = TailB->next;
28             len2++;
29         }
30         
31         if(TailA != TailB) return NULL;
32         
33         ListNode *NodeA = headA;
34         ListNode *NodeB = headB;
35         if(len1 > len2)
36         {
37             int k = len1 - len2;
38             while(k--)
39                 NodeA = NodeA->next;
40         }
41         else
42         {
43             int k = len2 - len1;
44             while(k--)
45                 NodeB = NodeB->next;
46         }
47         
48         while(NodeA != NodeB)
49         {
50         NodeA = NodeA->next;
51         NodeB = NodeB->next;
52         }
53         return NodeA;
54     }
55 };

 

以上是关于160. Intersection of Two Linked Lists的主要内容,如果未能解决你的问题,请参考以下文章

160. Intersection of Two Linked Lists

160. Intersection of Two Linked Lists

Leetcode 160:Intersection of Two Linked Lists

160. Intersection of Two Linked Listseasy

160. Intersection of Two Linked Lists

160. Intersection of Two Linked Lists