Friday, November 6, 2015

[leetcode]Intersection of Two Linked Lists

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        int lengthA = 0;
        ListNode runner = headA;
        while (runner != null){
            lengthA++;
            runner = runner.next;
        } 
        int lengthB = 0;
        runner = headB;
        while (runner != null){
            lengthB++;
            runner = runner.next;
        }

        for (int i = 0; i < lengthA-lengthB; i++, headA = headA.next);
        for (int i = 0; i < lengthB-lengthA; i++, headB = headB.next);
        while (headA != null){
            if (headA == headB) return headA;
            headA = headA.next;
            headB = headB.next;
        }

        return null;
    }
}

No comments:

Post a Comment