Java Solution


  • 0
    V
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode currentA = headA ;
            ListNode currentB = headB ;
            int l1 = 0 ;
            int l2 = 0 ;
            if(headA == null || headB == null){
                return null ;
            }
            while(currentA != null){
                l1 ++ ;
                currentA = currentA.next ;
            }
            while(currentB != null){
                l2 ++ ;
                currentB = currentB.next ;
            }
            ListNode currentAA = headA;
            ListNode currentBB = headB;
            ListNode result = null ;
            if(l1 == l2){
                while(currentAA != null && currentBB != null){
                    if(currentAA == currentBB){
                        result = currentAA ;
                        break;
                    }
                    currentAA = currentAA.next;
                    currentBB = currentBB.next;
                }
            }
            if(l1 > l2){
                int d = l1 - l2 ;
                result = traverse(currentAA , currentBB , d);
            }
            if(l2 > l1){
                int d = l2 - l1 ;
                result = traverse(currentBB , currentAA , d);
            }
            return result ;
            
        }
        
        public ListNode traverse(ListNode currentA , ListNode currentB , int d){
            int i = 0 ;
            ListNode result = null ;
            while(i != d){
                currentA = currentA.next;
                i ++ ;
            }
            while(currentA != null && currentB != null){
                if(currentA == currentB){
                    result = currentA;
                    break;
                }
                currentA = currentA.next;
                currentB = currentB.next;
            }
                
            return result ;
            
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

Log in to reply
 

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