首页 > 代码库 > Intersection of Two Linked Lists(java)

Intersection of Two Linked Lists(java)

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             else30             {31                 fast=fast.next;32                 slow=slow.next;33             }34         }35         return null;36     }37 }

 

Intersection of Two Linked Lists(java)