这个题暴露了一个基础知识问题:一开始写moveNSteps的时候返回的是void, 传入的head在经过method之后并没有真正发生改变,导致我主函数里面的head根本没移动,没有达到预期效果,导致wrong answer.
/**
* 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;
}
}