LeetCode-160 Intersection of Two Linked Lists

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.

For this problem, it is common to think of tuning the two list till they have equal length, and then starts to find the intersection part (as solution 1).

But a more clever idea is to loop thru both linked lists and switch the head of pointer if one reaches the end first.
Set the intersection part len=c, list A len= a+c, list B len=b+c
Since that (a+c)+(b+c) = (b+c)+(a+c),
The 2 lists will finally meet at the intersection part;
if there is no intersection, the 2 list will meet at Null, the end of lists. (c=0)

Solution 1

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pa=headA, pb=headB;
        int la=0,lb=0;

        while(pa!=null){
            la++;
            pa=pa.next;
        }
        while(pb!=null){
            lb++;
            pb=pb.next;
        }
        // compute the length of A and B

        pa=headA;
        pb=headB;

        if(la>lb){
            while(la!=lb){
                pa=pa.next;
                la--;
            }
        }else{
             while(la!=lb){
                pb=pb.next;
                lb--;
            }
        }
        // tune the length and then loop for common mnodes

        while(pa!=null&&pb!=null){
            if(pa==pb) return pa;
            // check if 2 nodes are the same (not just val?)
            pa=pa.next;
            pb=pb.next;
        }
        return null;
    }
}

Solution 2

Source

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    //boundary check
    if(headA == null || headB == null) return null;

    ListNode a = headA;
    ListNode b = headB;

    //if a & b have different len, then we will stop the loop after second iteration
    while( a != b){
        //for the end of first iteration, we just reset the pointer to the head of another linkedlist
        a = a == null? headB : a.next;
        b = b == null? headA : b.next;    
    }

    return a;
}