剑指Offer面试题52:两个链表的第一个公共节点(复习思路)

两种方法,一个是用两个辅助栈,另一个是获取长度。

    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;
    }

猜你喜欢

转载自blog.csdn.net/qq_40473204/article/details/114767319
今日推荐