/* * 160. Intersection of Two Linked Lists * 11.28 by Mingyang * 自己写的代码很长,但是话粗理不粗 */ public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int lenA = length(headA), lenB = length(headB); // move headA and headB to the same start point while (lenA > lenB) { headA = headA.next; lenA--; } while (lenA < lenB) { headB = headB.next; lenB--; } // find the intersection until end while (headA != headB) { headA = headA.next; headB = headB.next; } return headA; } private int length(ListNode node) { int length = 0; while (node != null) { node = node.next; length++; } return length; } /* * 那么下面是更加巧妙的方法,就是直接看两个不相等就继续走 * 知道一个走到null以后回到另一个list的开始继续走 * 第二次停止的时候刚好就是他们相遇的时候 */ public ListNode getIntersectionNode1(ListNode headA, ListNode headB) { //boundary check if(headA == null || headB == null) return null; 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; }