這個題暴露了一個基礎知識問題:一開始寫moveNSteps的時候返回的是void, 傳入的head在經(jīng)過method之后并沒有真正發(fā)生改變头镊,導致我主函數(shù)里面的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;
}
}