寻找公共节点

题目

https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof

解法

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
public class SO52_getIntersectionNode {
class ListNode {
int val;
ListNode next;
public ListNode(int x){
val =x;
next = null;
}
}

public static void main(String[] args) {

}

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;

int countA = 0;
int countB = 0;
ListNode pNodeA = headA, pNodeB = headB;
while (pNodeA != null) {
countA++;
pNodeA = pNodeA.next;
}
while (pNodeB != null) {
countB++;
pNodeB = pNodeB.next;
}
pNodeA = headA;
pNodeB = headB;
int dis = Math.abs(countA-countB);
if (countA > countB) {
while (dis != 0 ) {
pNodeA = pNodeA.next;
dis--;
}
} else if (countA < countB) {
while (dis != 0) {
pNodeB = pNodeB.next;
dis--;
}
}
while(pNodeA != null || pNodeB != null) {
if (pNodeA != pNodeB) {
pNodeA = pNodeA.next;
pNodeB = pNodeB.next;
} else {
break;
}
}
return pNodeA;
}

// 设交集链表长c,链表1除交集的长度为a,链表2除交集的长度为b,有
//a + c + b = b + c + a
//若无交集,则a + b = b + a
public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {

ListNode h1 = headA, h2 = headB;
while (h1 != h2) {

h1 = h1 == null ? headB : h1.next;
h2 = h2 == null ? headA : h2.next;
}

return h1;
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×