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

160. Intersection of Two Linked Lists

时间:2017-02-20 13:48:56      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:example   struct   write   sts   slow   无法   com   思路   java   

题目:

技术分享
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.
技术分享

链接:  http://leetcode.com/problems/intersection-of-two-linked-lists/

2/19/2017, Java

一开始的思路是,借用判断cycled linked list来。先从nodeA出发遍历,把最后一个node的next设为nodeB的head,这样第二次遍历时候通过slow, fast来找进入圈里的第一个node。

看起来很巧妙,但是是错误的,因为无法确定当fast, slow相遇时,是否是在进入圈里的第一个node,其实,可能为任一node。

正确解法,借鉴别人:

判断2个list的长度差,从距末尾相同长度开始(此时至少一个list是在head),一个个比较。

注意第一步之后要将a, b重新设到合理的位置,尤其是diff == 0时

 1 public class Solution {
 2     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 3         if (headA == null || headB == null) return null;
 4         int diff = 0;
 5         ListNode a = new ListNode(0);
 6         ListNode b = new ListNode(0);
 7         a = headA;
 8         b = headB;
 9         
10         while(a != null && b != null) {
11             a = a.next;
12             b = b.next;
13         }
14         while (a != null) {
15             diff++;
16             a = a.next;
17         }
18         while (b != null) {
19             diff--;
20             b = b.next;
21         }
22         if (diff > 0) {
23             a = headA;
24             while (diff > 0) {
25                 a = a.next;
26                 diff--;
27             }
28             b = headB;
29         } else if (diff < 0) {
30             b = headB;
31             while (diff < 0) {
32                 b = b.next;
33                 diff++;
34             }
35             a = headA;
36         } else {
37             a = headA;
38             b = headB;
39         }
40         
41         while (a != null && b != null) {
42             if (a == b) return a;
43             a = a.next;
44             b = b.next;
45         }
46         return null;
47     }
48 }

 

160. Intersection of Two Linked Lists

标签:example   struct   write   sts   slow   无法   com   思路   java   

原文地址:http://www.cnblogs.com/panini/p/6418745.html

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