Sword Finger Offer Interview Question 52: The first public node of the two linked lists (review ideas)

There are two methods, one is to use two auxiliary stacks, and the other is to get the length.

 

 

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int length_a = 0;
        int length_b = 0;
        ListNode temp_a = headA;
        ListNode temp_b = headB;
        while(temp_a!=null){
            length_a++;
            temp_a = temp_a.next;
        }
        while(temp_b!=null){
            length_b++;
            temp_b = temp_b.next;
        }
        temp_a = headA;
        temp_b = headB;
        if(length_a > length_b){
            for(int count = 0;count<length_a - length_b;count++){
                temp_a = temp_a.next;
            }
            for(int count = 0;count<length_b;count++){
                
                if(temp_a == temp_b){
                    return temp_a;
                }
                temp_a = temp_a.next;
                temp_b = temp_b.next;
            }
        }else{
            for(int count = 0;count<length_b - length_a;count++){
                temp_b = temp_b.next;
            }
            for(int count = 0;count<length_a;count++){
                
                if(temp_a == temp_b){
                    return temp_a;
                }
                temp_a = temp_a.next;
                temp_b = temp_b.next;
            }
        }
        return null;
    }

 

Guess you like

Origin blog.csdn.net/qq_40473204/article/details/114767319