/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ publicclassSolution{ public ListNode getIntersectionNode(ListNode headA, ListNode headB){ ListNode a = headA; ListNode b = headB; int lengthA = 0; int lengthB = 0; int start = 0; while(a!=null){ a = a.next; lengthA ++; } while(b!=null){ b = b.next; lengthB ++; } if(lengthA > lengthB){ b = headB; a = headA; int i = 0; while(i < lengthA - lengthB){ a = a.next; i ++; } } if(lengthB >= lengthA){ a = headA; b = headB; int i = 0; while(i < lengthB - lengthA){ b = b.next; i++; } } while(a != null && b != null){ if(a.val != b.val){ a = a.next; b = b.next; } else{ return a; } } returnnull; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
public ListNode getIntersectionNode(ListNode headA, ListNode headB){ //boundary check if(headA == null || headB == null) returnnull; ListNode a = headA; ListNode b = headB; //if a & b have different len, then we will stop the loop after second iteration while( a != b){ //for the end of first iteration, we just reset the pointer to the head of another linkedlist a = a == null? headB : a.next; b = b == null? headA : b.next; } return a; }