-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0160-intersection-of-two-linked-lists.java
More file actions
45 lines (41 loc) · 1.06 KB
/
0160-intersection-of-two-linked-lists.java
File metadata and controls
45 lines (41 loc) · 1.06 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (!AreMerged(headA, headB)) return null;
ListNode p1 = headA;
ListNode p2 = headB;
while(p1 != null && p2 != null) {
if (p1.equals(p2)) return p1;
p1 = p1.next;
p2 = p2.next;
if (p1 == null) {
p1 = headB;
}
if (p2 == null) {
p2 = headA;
}
}
return null;
}
public boolean AreMerged(ListNode p1, ListNode p2) {
if (p1.equals(p2)) return true;
if (p1 == null || p2 == null) return false;
while (p1.next != null) {
p1 = p1.next;
}
while (p2.next != null) {
p2 = p2.next;
}
return p1.equals(p2);
}
}