假设A自己私有的部分长度是m, B是n, 公用的部分是x, (m < n) 通过A, B同时向前走, A走完的时候, B停在离终点还有n - m步骤, 这个时候再让B head n-m步, 这个时候, 两个链表向前走一起向前走m步就会相遇, 也就是一起向前走就会相遇
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode h1 = headA, h2 = headB; while (h1 != null && h2 != null) { h1 = h1.next; h2 = h2.next; } if (h2 == null) { ListNode tmp = headA; headA = headB; headB = tmp; } ListNode p = h1 != null ? h1 : h2; while (p != null) { p = p.next; headB = headB.next; } while (headA != null && headB != null) { if (headA == headB) { return headA; } headA = headA.next; headB = headB.next; } return null; } }
|