My long but easy code in java


  • 0
    J
    if(headA==null||headB==null)return null;
    int l1=1;
    int l2=1;
    ListNode p=headA;
    ListNode q=headB;
    ListNode l=null;
    ListNode s=null;
    while(p.next!=null){
    	p=p.next;
    	l1++;
    }
    while(q.next!=null){
    	q=q.next;
    	l2++;
    }
    if(l1>l2){
    	l=headA;
    	s=headB;
    	for(int i=0;i<l1-l2;i++){
    		l=l.next;
    	}
    	for(int j=0;j<l2;j++){
    		if(l==s)return l;
    		l=l.next;
    		s=s.next;
    	}
    }
    if(l1<l2){
    	l=headB;
    	s=headA;
    	for(int i=0;i<l2-l1;i++){
    		l=l.next;
    	}
    	for(int j=0;j<l1;j++){
    		if(l==s)return l;
    		l=l.next;
    		s=s.next;
    	}
    }
    if(l1==l2){
    	l=headB;
    	s=headA;
    	for(int i=0;i<l1;i++){
    		if(l==s)return l;
    		l=l.next;
    		s=s.next;
    	}
    }
    return null;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.