2ブラシ160.Intersection of Two Linked Lists

1637 ワード

この問題は基礎知識の問題を暴露した:moveNStepsを書き始めたときに戻ったのはvoidで、伝わったheadはmethodを経てから本当に変わっていないので、私の主関数の中のheadは全然移動していないで、予想の効果に達していないで、wrong answerを招きました.
image.png
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null){
            return null;
        }
        int lenA = getLen(headA);
        int lenB = getLen(headB);
        int diff = 0;
        if (lenA > lenB){
            diff = lenA - lenB;
            headA = moveNSteps(headA, diff);
        } else if (lenA < lenB){
            diff = lenB - lenA;
            headB = moveNSteps(headB, diff);
        }
        System.out.println(diff);
        System.out.println(headA.val);
        System.out.println(headB.val);
        while (headA != null && headB != null){
            if (headA == headB){
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
    
    private int getLen(ListNode head){
        int count = 0;
        ListNode curt = head;
        while (curt != null){
            curt = curt.next;
            count++;
        }
        return count;
    }
    
    private ListNode moveNSteps(ListNode head, int diff){
        while (diff > 0 && head != null){
            head = head.next;
            diff--;
        }  
        return head;
    }
}