|
| 1 | +package me.ramswaroop.linkedlists; |
| 2 | + |
| 3 | +import me.ramswaroop.common.SingleLinkedList; |
| 4 | +import me.ramswaroop.common.SingleLinkedNode; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by IntelliJ IDEA. |
| 8 | + * |
| 9 | + * @author: ramswaroop |
| 10 | + * @date: 7/9/15 |
| 11 | + * @time: 4:00 PM |
| 12 | + */ |
| 13 | +public class TripletFromThreeLinkedLists { |
| 14 | + |
| 15 | + public static SingleLinkedNode<Integer> findTripletWithSumEqualsTo(SingleLinkedNode<Integer> node1, |
| 16 | + SingleLinkedNode<Integer> node2, |
| 17 | + SingleLinkedNode<Integer> node3, |
| 18 | + int sum) { |
| 19 | + node2 = MergeSort.mergeSort(node2); |
| 20 | + node3 = MergeSort.mergeSort(node3); |
| 21 | + node3 = ReverseSingleLinkedList.recursiveReverseList(node3); |
| 22 | + |
| 23 | + SingleLinkedNode<Integer> curr1 = node1, curr2, curr3; |
| 24 | + int s; |
| 25 | + |
| 26 | + while (curr1 != null) { |
| 27 | + |
| 28 | + curr2 = node2; |
| 29 | + curr3 = node3; |
| 30 | + |
| 31 | + while (curr2 != null && curr3 != null) { |
| 32 | + s = curr1.item + curr2.item + curr3.item; |
| 33 | + |
| 34 | + if (s == sum) { |
| 35 | + curr1.next = curr2; |
| 36 | + curr2.next = curr3; |
| 37 | + curr3.next = null; |
| 38 | + return curr1; |
| 39 | + } |
| 40 | + |
| 41 | + if (s < sum) { |
| 42 | + curr2 = curr2.next; |
| 43 | + } else { |
| 44 | + curr3 = curr3.next; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + curr1 = curr1.next; |
| 49 | + |
| 50 | + } |
| 51 | + |
| 52 | + return null; |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | + public static void main(String a[]) { |
| 57 | + SingleLinkedList<Integer> linkedList1 = new SingleLinkedList<>(); |
| 58 | + linkedList1.add(2); |
| 59 | + SingleLinkedList<Integer> linkedList2 = new SingleLinkedList<>(); |
| 60 | + linkedList2.add(6); |
| 61 | + linkedList2.add(8); |
| 62 | + linkedList2.add(7); |
| 63 | + SingleLinkedList<Integer> linkedList3 = new SingleLinkedList<>(); |
| 64 | + linkedList3.add(9); |
| 65 | + linkedList3.add(6); |
| 66 | + linkedList3.add(12); |
| 67 | + linkedList1.printList(); |
| 68 | + linkedList2.printList(); |
| 69 | + linkedList3.printList(); |
| 70 | + SingleLinkedList.printList(findTripletWithSumEqualsTo(linkedList1.head, |
| 71 | + linkedList2.head, |
| 72 | + linkedList3.head, |
| 73 | + 18)); |
| 74 | + } |
| 75 | +} |
0 commit comments