leetcode
leetcode copied to clipboard
160. intersectionOfTwoLinkedLists.cpp
There is no swap method included, while you use swap(headA, headB).
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;
}
}
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;
}
};