lintcode-medium-Intersetion of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

 

The following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;      
 *     }
 * }
 */
public class Solution {
    /**
     * @param headA: the first list
     * @param headB: the second list
     * @return: a ListNode 
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        // Write your code here
        
        if(headA == null || headB == null)
            return null;
        
        ListNode p1 = headA;
        ListNode p2 = headB;
        
        int len1 = 0;
        int len2 = 0;
        
        while(p1 != null){
            len1++;
            p1 = p1.next;
        }
        
        while(p2 != null){
            len2++;
            p2 = p2.next;
        }
        
        p1 = headA;
        p2 = headB;
        
        if(len1 > len2){
            for(int i = 0; i < len1 - len2; i++)
                p1 = p1.next;
        }
        else if(len2 > len1){
            for(int i = 0; i < len2 - len1; i++)
                p2 = p2.next;
        }
        
        while(p1 != null && p2 != null && p1 != p2){
            p1 = p1.next;
            p2 = p2.next;
        }
        
        
        return p1;
    }  
}

 

posted @ 2016-03-23 09:01  哥布林工程师  阅读(139)  评论(0编辑  收藏  举报