Sunday, January 4, 2015

Intersection of Two Linked Lists (LeetCode Linked List)

Question:  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.

Idea:  Assume the length of A and B can be denoted as
aTotal= unmatchedA+commonC
bTotal=unmatchedB+commonC.
Then aTotal-bTotal=unmatchedA-unmatchedB. Without loss of generality, let us assume is longer. Then can know the unmatched part of A is aTotal-bTotal longer than the unmatched part B. Therefore we just need to skip the first aTotal-bTotal nodes in A to make A and B aligned. Then we traversal A and B simultaneously until they meet. If they did not meet before reaching null, return null.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode getIntersectionNode(ListNode headA, ListNode headB) {  
     int lenA=getLength(headA);  
     int lenB=getLength(headB);  
     if(lenA>lenB)  
     {  
       for(int i=0;i<lenA-lenB;i++)  
         headA=headA.next;  
     }  
     if(lenA<lenB)  
     {  
       for(int i=0;i<lenB-lenA;i++)  
         headB=headB.next;  
     }  
     while(headA!=null&&headB!=null)  
     {  
       if(headA==headB)  
         return headA;  
       headA=headA.next;  
       headB=headB.next;  
     }  
     return null;  
   }  
   public int getLength(ListNode head)  
   {  
     int counter=0;  
     while(head!=null)  
     {  
       counter+=1;  
       head=head.next;  
     }  
     return counter;  
   }  
 }  

No comments:

Post a Comment