My Easy to Understand Java Solution Accepted


  • -7
    K
    public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        
        if(headA == null)   return headA;
        
        if(headB == null)   return headB;
    
        while(headA!=null && headB!=null){
            
            if(headA.val == headB.val)
                return headA;
                
            if(headA.val<headB.val)
                headA=headA.next;
            else
                headB=headB.next;
       
        }
               
        return null;
    
    }
    

    }


  • 2
    M

    Quick Clarification : How did you assume the linked list was a sorted singly linked list ??


  • 0
    K

    Because there cannot be an intersection otherwise ! Think about it logically why would there be two lists intersecting at a point if they weren't in the sorted order. I don't know how to explain it better. But the fact that they "intersect" made me think it has to be sorted. If someone could explain this better please do !


  • 0
    J

    @mindheist's point makes sense. and also, you changed the structure of headA and headB. i don't know why your solution got accepted. think about this case: list1---2-5-6-4-9; 1-2-8-6-4-9.


  • 0
    M

    @kartikey - Well take a look at @jaciliu's case above ; there are two lists , neither of them sorted , but they have a point of intersection , and rest of the elements from that point of intersection are the same !


  • 0
    M

    @jaciliu - good example !


  • 0
    K

    @mindheist I totally agree with that point of @jaciliu but to me it seemed natural for them to be in order to have an intersection. Again I agree I have made a very very strong assumption here and I also agree with the points given.

    As for the part of changing the head pointers. That is bad coding but for the purpose of solving the problems it does the job. Would I do that in the real world ? NO !


Log in to reply
 

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