-
Notifications
You must be signed in to change notification settings - Fork 19
/
IntersectionOfTwoLinkedLists.java
65 lines (54 loc) · 1.31 KB
/
IntersectionOfTwoLinkedLists.java
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
60
61
62
63
64
65
package oj.leetcode;
/**
* 160. Intersection of Two Linked Lists
* Created by vonzhou on 2019/2/17.
*/
public class IntersectionOfTwoLinkedLists {
/**
* AC
* A,B如果长度不一样的话,较长的链表先略过一定的部分,然后2个链表共同前进,看节点是否一样
*/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
int lenA = 0;
int lenB = 0;
ListNode p = headA;
ListNode q = headB;
while (p != null) {
p = p.next;
lenA++;
}
while (q != null) {
q = q.next;
lenB++;
}
int diff = 0;
p = headA;
q = headB;
if (lenA > lenB) {
diff = lenA - lenB;
int i = 0;
while (i < diff) {
p = p.next;
i++;
}
} else {
diff = lenB - lenA;
int i = 0;
while (i < diff) {
q = q.next;
i++;
}
}
while (p != null && q != null) {
if (p == q) {
return p;
}
p = p.next;
q = q.next;
}
return null;
}
}