码迷,mamicode.com
首页 > 其他好文 > 详细

160. Intersection of Two Linked Lists

时间:2017-10-29 17:36:44      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:deb   rabl   solution   win   class   adb   origin   which   blog   

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

标签:deb   rabl   solution   win   class   adb   origin   which   blog   

原文地址:http://www.cnblogs.com/xumh/p/7750437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!