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 };

 

posted @ 2017-10-29 17:00  绿宝宝怪  阅读(135)  评论(0编辑  收藏  举报
#site_nav_under,#ad_under_post_holder,#under_post_news,#google_ad_c2,#under_post_kb{ width:0; height:0; display:none; overflow:hidden; }