-
Notifications
You must be signed in to change notification settings - Fork 62
/
IntersectionLinkedList.java
46 lines (40 loc) · 1.07 KB
/
IntersectionLinkedList.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
package datastructure.linkedlist.leetcode;
import java.util.HashSet;
import java.util.Set;
/**
* @author roseduan
* 链表的交点
*/
public class IntersectionLinkedList {
public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
ListNode p = headA;
while (p != null) {
set.add(p);
p = p.next;
}
ListNode q = headB;
while (q != null) {
if (set.contains(q)) {
return q;
}
q = q.next;
}
return null;
}
public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
ListNode p = headA, q = headB;
while (p != q) {
p = p == null ? headB : p.next;
q = q == null ? headA : q.next;
}
return p;
}
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
}