-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindFirstCommonNode.java
More file actions
62 lines (56 loc) · 1.78 KB
/
FindFirstCommonNode.java
File metadata and controls
62 lines (56 loc) · 1.78 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
60
61
62
package com.company;
import org.junit.Test;
public class FindFirstCommonNode {
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public int getListNodeLength(ListNode pHead) {
int count = 0;
while (pHead != null) {
count++;
pHead = pHead.next;
}
return count;
}
//输入两个链表,找出它们的第一个公共结点。
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int pHead1Length = getListNodeLength(pHead1);
int pHead2Length = getListNodeLength(pHead2);
if (pHead1Length == 0 || pHead2Length == 0) return null;
if (pHead1Length < pHead2Length) {
ListNode tmp = pHead1;
pHead1 = pHead2;
pHead2 = tmp;
}
for (int i = 0; i < Math.abs(pHead1Length - pHead2Length); i++) {
pHead1 = pHead1.next;
}
while (pHead1 != null && pHead2 != null && pHead1 != pHead2) {
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return pHead1;
}
@Test
public void test() {
// 公共结点是第一个结点
// 1 - 2 - 3 - 4 - 5
// 两个链表完全重合
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
ListNode n4 = new ListNode(4);
ListNode n5 = new ListNode(5);
ListNode n6 = new ListNode(6);
ListNode n7 = new ListNode(7);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
System.out.println(FindFirstCommonNode(n1, n1).val); // 1
}
}