* 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;}
ListNode currentHeadA = headA;
ListNode currentHeadB = headB;
int count = 0;
while(currentHeadA != currentHeadB)
{
if (currentHeadA.next == null ) {
currentHeadA = headB;
count++;
} else {
currentHeadA = currentHeadA.next;
}
currentHeadB = currentHeadB.next != null ? currentHeadB.next : headA;
if (count > 1) {
return null;
}
}
return currentHeadA;
}
}
评论