-
Notifications
You must be signed in to change notification settings - Fork 1
/
No160相交链表.java
83 lines (75 loc) · 2.14 KB
/
No160相交链表.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package leetCode.repository;
/**
*
* @author jiangxiewei
* @since 2022/4/8
*/
public class No160相交链表 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
return superDoublePointer(headA, headB);
}
/**
* 官方题解二的双指针, 通过指针Pa或Pb移动到头后循环到另一个链表的起始点上达成移动量一致
*
* @param headA 链表A的起始节点
* @param headB 链表B的起始节点
* @return 相交的链表
*/
public ListNode superDoublePointer(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode pa = headA, pb = headB;
while (pa != pb) {
pa = pa == null ? headB : pa.next;
pb = pb == null ? headA : pb.next;
}
return pa;
}
/**
* aSum = a链表求和, bSum = b链表求和
* 然后开始移动a和b的指针Pa和Pb
* 每移动一下,减少aSum或bSum的值,当相等时,一起移动两个指针. 直到移动到相同的节点上
* 通过求和的方式来判断两侧指针偏移情况
* @param headA a链表
* @param headB b链表
* @return 目标节点
*/
private ListNode sumValueToMoveP(ListNode headA, ListNode headB) {
int aSum = getListSum(headA);
int bSum = getListSum(headB);
while (headA != null && headB != null) {
if (headA == headB) {
return headA;
}
if (aSum >= bSum) {
aSum -= headA.val;
headA = headA.next;
}
if (aSum <= bSum) {
bSum -= headB.val;
headB = headB.next;
}
}
return null;
}
private int getListSum(ListNode node) {
int sum = 0;
while (node != null) {
sum += node.val;
node = node.next;
}
return sum;
}
/**
* 题目提供的节点
*/
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
}