19
19
B: b1 → b2 → b3
20
20
begin to intersect at node c1.
21
21
22
+ Example 1:
23
+ A: 4 → 1
24
+ ↘
25
+ 8 → 4 → 5
26
+ ↗
27
+ B: 5 → 0 → 1
28
+
29
+
30
+ Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
31
+ Output: Reference of the node with value = 8
32
+ Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
33
+ From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5].
34
+ There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
35
+
36
+
37
+ Example 2:
38
+ A: 0 -> 9 → 1
39
+ ↘
40
+ 2 → 4
41
+ ↗
42
+ B: 3
43
+
44
+ Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
45
+ Output: Reference of the node with value = 2
46
+ Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
47
+ From the head of A, it reads as [0,9,1,2,4]. From the head of B, it reads as [3,2,4].
48
+ There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
49
+
50
+
51
+ Example 3:
52
+ A: 2 → 6 -> 4
53
+
54
+ B: 1 -> 5
55
+
56
+ Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
57
+ Output: null
58
+ Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5].
59
+ Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
60
+ Explanation: The two lists do not intersect, so return null.
61
+
22
62
23
63
Notes:
64
+
24
65
If the two linked lists have no intersection at all, return null.
25
66
The linked lists must retain their original structure after the function returns.
26
67
You may assume there are no cycles anywhere in the entire linked structure.
@@ -66,6 +107,8 @@ private int findLen(ListNode head) {
66
107
67
108
public static class Solution2 {
68
109
/**
110
+ * Most optimal solution:
111
+ *
69
112
* O(m+n) time
70
113
* O(1) space
71
114
* credit: https://discuss.leetcode.com/topic/28067/java-solution-without-knowing-the-difference-in-len*/
@@ -77,7 +120,9 @@ public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
77
120
ListNode a = headA ;
78
121
ListNode b = headB ;
79
122
123
+ /**if a and b have different lengths, then it will stop the loop after second iteration*/
80
124
while (a != b ) {
125
+ /**for the first iteration, it'll just reset the pointer to the head of another linkedlist*/
81
126
a = a == null ? headB : a .next ;
82
127
b = b == null ? headA : b .next ;
83
128
}
0 commit comments