My Java solution


  • 0
    H

    A little dumb but straight forward.

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
           ListNode p1 = headA;
    		ListNode p2 = headB;
    		int i = 0;
    		int j = 0;
    		while(p1 != null){
    			i++;
    			p1 = p1.next;
    		}
    		while(p2 != null){
    			j++;
    			p2 = p2.next;
    		}
    		
    		p1 = headA;
    		p2 = headB;
    		if(i > j){
    			while(i > j){
    				p1 = p1.next;
    				i--;
    			}
    		}
    		if(i < j){
    			while(i < j){
    				p2 = p2.next;
    				j--;
    			}
    		}
    		
    		while(i > 0){
    			if(p1 == p2){
    				return p1;
    			} else{
    				p1 = p1.next;
    				p2 = p2.next;
    				i--;
    			}
    		}
    		
    		return null;
        }

Log in to reply
 

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