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

leetcode. Intersection of Two Linked Lists

时间:2014-12-04 00:38:30      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   on   

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.

只需要将listB首位相连,这样listA和listB就形成了一个带有环的链表。

这样题目就变成了Linked List Cycle II

 1 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) 
 2     {
 3         ListNode *tail, *join;
 4         if (headA == NULL || headB == NULL)
 5             return NULL;
 6             
 7         for (tail = headB; tail->next != NULL; tail = tail->next); // reach tail
 8         tail->next = headB; // create a circle
 9         join = detectCycle(headA);
10         tail->next = NULL; // keep list B as original
11         
12         return join;
13     }
14     
15     ListNode *detectCycle(ListNode *head)
16     {
17         ListNode *fast = head, *slow = head;
18         
19         while (fast != NULL)
20         {
21             slow = slow->next;
22             fast = fast->next;
23             if (fast != NULL)
24                 fast = fast->next;
25             if (fast != NULL && fast == slow) // catch slow
26                 break;
27         }
28         
29         if (fast == NULL)
30             return NULL;
31             
32         slow = head;
33         while (slow != fast)
34         {
35             slow = slow->next;
36             fast = fast->next;
37         }
38         return slow;
39     }

 

leetcode. Intersection of Two Linked Lists

标签:style   blog   http   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/ym65536/p/4141555.html

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