My java solution


  • 0
    X
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if(headA == null || headB == null){
                return null;
            }
            int length1=0;
            int length2=0;
            
            ListNode head1 = headA;
            ListNode head2 = headB;
            while(headA!=null){
                length1++;
                headA = headA.next;
            }
            while(headB!=null){
                length2++;
                headB = headB.next;
            }
            int minus = length1-length2;
            int abs = Math.abs(minus);
            if(minus<0){
                int step=abs;
                while(step>0){
                    head2 = head2.next;
                    step--;
                }
            }else{
                int step=abs;
                while(step>0){
                    head1 = head1.next;
                    step--;
                }
            }
            if(head1==head2){
                return head1;
            }
            while(head1!=null&&head2!=null&&head1!=head2){
                head1= head1.next;
                head2= head2.next;
            }
            
            return head1;
            
        }
    }

Log in to reply
 

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