Friday, October 30, 2015

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

-----------------------------------------
----------------------------------------
1. find the length of two lists: lenA , lenB,
(after 1, we can check whether a connection exist or not by checking the final nodes of the two lists are the same or not. If not, return directly!)
2. using two pointers pa, pb. Move the pointer forward along the longer list by abs(lenA-lenB) nodes. 
3. then move both pointers ahead step by step and check whether there is a intersection. 
NOTE 1:
 a case below:
when only one node exist and is also the intersection:
pa->[1]<-pb
NOTE 2:
when pa->NULL,
           pb->NULL,
then we have   pa==pb???. The answer is yes!!
////////////////////////////////////////////////////////////////
//codes
class Solution {
public:
       ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
              //check input
              if (headA == NULL || headB == NULL)return NULL;
              //find the length of two list
              ListNode *pa = headA, *pb = headB;
              int countA = 0, countB = 0;
              while (pa != NULL){
                     pa = pa->next;
                     countA++;
              }
              while (pb != NULL){
                     pb = pb->next;
                     countB++;
              }
              //check there are intersection or not
              if (pa != pb)return NULL;
              //move pointer forward by abs(countA-countB)
              pa = headA;
              pb = headB;
              if (countA>countB){
                     for (int i = 0; i<countA - countB; i++){
                           pa = pa->next;
                     }
              }
              else{
                     for (int i = 0; i<countB - countA; i++){
                           pb = pb->next;
                     }
              }
              //FIND THE INTERSECTION NODE
              while (pa!= NULL){
                     if (pa == pb)return pa;
                     else{
                           pa = pa->next;
                           pb = pb->next;
                     }
              }
       }
};



No comments:

Post a Comment