码迷,mamicode.com
首页 > 编程语言 > 详细

Intersection of Two Linked Lists(java)

时间:2015-01-19 19:00:26      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

eg:        a1 → a2
                 ↘
                     c1 → c2 → c3 或者直接a1 → b1
          ↗ 
    b1 → b2 → b3
求公共链表c1.

常规的指针分裂法,复制法,偏移法。
 1 public class Solution {
 2     public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 3         if(headA==null||headB==null) return null;
 4         int lengthA=0;
 5         int lengthB=0;
 6         ListNode currentA=headA;
 7         ListNode currentB=headB;
 8         while(currentA.next!=null)
 9         {
10             currentA=currentA.next;
11             lengthA++;
12         }
13          while(currentB.next!=null)
14         {
15              currentB=currentB.next;
16             lengthB++;
17         }
18         ListNode fast=lengthA>lengthB?headA:headB;
19         ListNode slow=lengthA>lengthB?headB:headA;
20         for(int i=0;i<Math.abs(lengthA-lengthB);i++)
21         {
22             fast=fast.next;
23         }
24 
25         while(fast!=null)
26         {
27             if(fast==slow)
28             return fast;
29             else
30             {
31                 fast=fast.next;
32                 slow=slow.next;
33             }
34         }
35         return null;
36     }
37 }

 

Intersection of Two Linked Lists(java)

标签:

原文地址:http://www.cnblogs.com/sweetculiji/p/4234419.html

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