Insersection of Two Linked Lists

Posted on

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.

public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if (headA == null || headB == null) {return null;}
int lenA = getLen(headA);        int lenB = getLen(headB);        while (headA != null && headB != null) {        if (lenA > lenB) {        headA = headA.next;        lenA -= 1;        } else if (lenA < lenB) {        headB = headB.next;        lenB -= 1;        } else {        if (headA == headB) {        return headA;        }         headA = headA.next;        headB = headB.next;        lenA -= 1;        lenB -= 1;        }        }
return null;    }    public static int getLen(ListNode head) {    int len = 0;    while (head != null) {    len += 1;    head = head.next;    }    return len;    }


This problem is about traversing the linked list. Use the length of the list to mark the progress. My way of solution is a common one and the complexity is O(m+n).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s