-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathIntersectionOfTwoLinkedLists.java
More file actions
44 lines (43 loc) · 1.02 KB
/
IntersectionOfTwoLinkedLists.java
File metadata and controls
44 lines (43 loc) · 1.02 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class IntersectionOfTwoLinkedLists {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode na = headA;
ListNode nb = headB;
while (na != null && nb != null) {
na = na.next;
nb = nb.next;
}
if (na == null) {
ListNode temp = nb;
nb = headB;
while (temp != null) {
temp = temp.next;
nb = nb.next;
}
na = headA;
} else if (nb == null) {
ListNode temp = na;
na = headA;
while (temp != null) {
temp = temp.next;
na = na.next;
}
nb = headB;
}
while (na != nb) {
na = na.next;
nb = nb.next;
}
return na;
}
}