leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

160. intersectionOfTwoLinkedLists.cpp

Open PYQ0423 opened this issue 6 years ago • 2 comments

There is no swap method included, while you use swap(headA, headB).

PYQ0423 avatar Aug 30 '19 07:08 PYQ0423

public class Solution {
    public ListNode getIntersectionNode(ListNode head1, ListNode head2) {
        int c1=getCount(head1);
        int c2=getCount(head2);
        
        if(c1>c2){
            int d=c1-c2;
            return getShift(d , head1 , head2);
        }else{
            int d= c2-c1;
            return getShift(d, head2, head1);
        }
        
    }
   public static int getCount(ListNode head){
       int count=0;
       while(head!=null){
           count++;
           head=head.next;
       }
       return count;
   }
    
    public static ListNode getShift(int d, ListNode head1 , ListNode head2){
       
        ListNode curr1=head1, curr2=head2;
        //head1 is greater
        for( int i =0;i< d; i++ ){
            curr1=curr1.next;
        }
        
        while(curr1!=null){
            if(curr1==curr2){
                return curr1;
            }
            curr1=curr1.next;
            curr2=curr2.next;
        }
        return null;
    }
}

Gurpreet-Saini avatar Apr 20 '22 19:04 Gurpreet-Saini

class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode *temp=headA; ListNode *temp2=headB; while(temp!=temp2){ if(temp==NULL) temp=headB; else temp=temp->next; if(temp2==NULL) temp2=headA; else temp2=temp2->next;

    }return temp;
}

};

Debmalya017Das avatar Feb 26 '23 14:02 Debmalya017Das