-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetIntersectionNode.java
More file actions
59 lines (51 loc) · 1.42 KB
/
Copy pathGetIntersectionNode.java
File metadata and controls
59 lines (51 loc) · 1.42 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
47
48
49
50
51
52
53
54
55
56
57
58
59
package self;
/**
* @author qiaoying
* @date 2019-04-17 10:19
*/
public class GetIntersectionNode {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode list1 = headA;
ListNode list2 = headB;
int length1 = 0;
int length2 = 0;
while (list1 != null) {
length1++;
list1 = list1.next;
}
while (list2 != null) {
length2++;
list2 = list2.next;
}
if (length1 > length2) {
int gap = length1 - length2;
list1 = headA;
list2 = headB;
for (int i = 0; i < gap; i++) {
list1 = list1.next;
}
} else {
int gap = length2 - length1;
list1 = headA;
list2 = headB;
for (int i = 0; i < gap; i++) {
list2 = list2.next;
}
}
while (list1 != list2 ) {
list1 = list1.next;
list2 = list2.next;
}
return list1;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(1);
ListNode node3 = new ListNode(1);
ListNode node4 = new ListNode(1);
ListNode node5 = new ListNode(1);
ListNode node6 = new ListNode(1);
ListNode node7 = new ListNode(1);
ListNode node8 = new ListNode(1);
}
}