-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTripletSum.java
More file actions
38 lines (33 loc) · 1.09 KB
/
TripletSum.java
File metadata and controls
38 lines (33 loc) · 1.09 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
package DoublyLinkedList;
import java.util.ArrayList;
public class TripletSum {
public ArrayList<ArrayList<Integer>> tripletSumInLinkedList(Node head, int sum) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
Node s, m, e;
s = head;
e = head;
// Assigning e to the tail node.
while (e.next != null) e = e.next;
while (s.next.next != null) {
int currSum = sum - s.data;
m = s.next;
Node ev = e;
while (m != null && ev != null && m != ev) {
int newSum = m.data + ev.data;
if (newSum == currSum) {
ArrayList<Integer> triple = new ArrayList<>();
triple.add(s.data);
triple.add(m.data);
triple.add(ev.data);
res.add(triple);
m = m.next;
} else if (newSum > currSum)
ev = ev.prev;
else
m = m.next;
}
s = s.next;
}
return res;
}
}