-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersectionNodeOfTwoList.java
More file actions
46 lines (37 loc) · 1 KB
/
IntersectionNodeOfTwoList.java
File metadata and controls
46 lines (37 loc) · 1 KB
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
package LinkedLists;
public class IntersectionNodeOfTwoList {
public static Node getIntersectionNode(Node headA, Node headB) {
Node tempA = headA;
Node tempB = headB;
int lengthA = 0, lengthB = 0;
while (tempA != null) {
lengthA++;
tempA = tempA.next;
}
while (tempB != null) {
lengthB++;
tempB = tempB.next;
}
// Reinitialize.
tempA = headA;
tempB = headB;
if (lengthA > lengthB) {
int steps = lengthA - lengthB;
for (int i = 0; i < steps; i++) {
tempA = tempA.next;
}
} else {
int steps = lengthB - lengthA;
for (int i = 0; i < steps; i++) {
tempB = tempB.next;
}
}
while (tempA != tempB) {
tempA = tempA.next;
tempB = tempB.next;
}
return tempA;
}
public static void main(String[] args) {
}
}