Intersection Linked List Java Solution


  • 3
    V

    public class Solution {

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    
        if(headA == null || headB == null){
            return null;
        }
        
        int lenA = 0;
        int lenB = 0;
        ListNode lenforA = headA;
        ListNode lenforB = headB;
        
        while(lenforA != null){
            lenforA = lenforA.next;
            lenA++;
        }
        while(lenforB != null){
            lenforB = lenforB.next;
            lenB++;
        }
        
        if(lenA > lenB){
            int move1 = lenA - lenB;
            while(move1 != 0){
                headA = headA.next;
                move1--;
            }
        }
        
        if(lenA < lenB){
            int move2 = lenB - lenA;
            while(move2 != 0){
                headB = headB.next;
                move2--;
            }
        }
        
        while(headA != null && headB != null){
            if(headA == headB){
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }
        
        return null;
    }
    

    }


  • 0
    O

    "The linked lists must retain their original structure after the function returns."
    Does it mean you may still use "lenforB = lenforB.next;" instead of "headA = headA.next;" in the last three loop?


  • 0
    V

    Oh I should use another two variables instead of using headA and headB directly in the last three while loop ! Or it will damage the structure of these two linked list ! You are right ! Thank you !


Log in to reply
 

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