-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersectionOfTwoSinglyLinkedlists.java
More file actions
53 lines (48 loc) · 1.57 KB
/
Copy pathIntersectionOfTwoSinglyLinkedlists.java
File metadata and controls
53 lines (48 loc) · 1.57 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
import java.util.HashSet;
public class IntersectionOfTwoSinglyLinkedlists {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static void main(String[] args) {
ListNode headA = new ListNode(4);
ListNode headB = new ListNode(5);
ListNode node1 = new ListNode(8);
ListNode node2 = new ListNode(1);
ListNode node3 = new ListNode(4);
ListNode node4 = new ListNode(5);
ListNode node5 = new ListNode(6);
ListNode node6 = new ListNode(1);
headA.next = node1;
headA.next.next = node2;
headA.next.next.next = node3;
headA.next.next.next.next = node4;
headA.next.next.next.next.next = node5;
headA.next.next.next.next.next.next = node6;
headB.next = node4;
headB.next.next = node5;
headB.next.next.next = node6;
System.out.println(solution(headA, headB).val);
}
public static ListNode solution(ListNode headA, ListNode headB) {
HashSet<ListNode> mySet = new HashSet<>();
ListNode currentA = headA;
ListNode currentB = headB;
while (currentA != null && currentA.next != null) {
mySet.add(currentA);
currentA = currentA.next;
}
while (currentB != null && currentB.next != null) {
if (mySet.contains(currentB)) {
return currentB;
} else {
currentB = currentB.next;
}
}
return null;
}
}