-
Notifications
You must be signed in to change notification settings - Fork 0
/
160. Intersection of Two Linked Lists
75 lines (65 loc) · 1.63 KB
/
160. Intersection of Two Linked Lists
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
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
a1 - a2 - a3
c1 - c2 - c3
b1 - b2
begin to intersect at node c1.
*/
/*
Idea:
a + c + b = b + c + a
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA;
ListNode b = headB;
boolean aEnd = false;
boolean bEnd = false;
while(a != null && b != null){
if(a.next == null && aEnd == false){
a = headB;
aEnd = true;
}
if(b.next == null && bEnd == false){
b = headA;
bEnd = true;
}
if(a == b && aEnd && bEnd){
return a;
}
a = a.next;
b = b.next;
}
return null;
}
}
/**
* 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) {
HashSet<ListNode> nodesA = new HashSet<>();
ListNode current = headA;
while (current != null) {
nodesA.add(current);
current = current.next;
}
current = headB;
while (current != null) {
if (nodesA.contains(current)) {
return current;
}
current = current.next;
}
return null;
}
}