Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 3bdf192

Browse files
author
Ram swaroop
committed
maximum sum path: done
1 parent c7017d0 commit 3bdf192

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed

src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package me.ramswaroop.linkedlists;
22

3+
import me.ramswaroop.common.SingleLinkedList;
34
import me.ramswaroop.common.SingleLinkedNode;
45

56
/**
@@ -14,15 +15,15 @@ public class MaximumSumLinkedList {
1415
/**
1516
* Constructs a linked list that contains maximum sum path from start to end
1617
* from two linked lists starting at {@param node1} and {@param node2}.
17-
*
18+
* <p/>
1819
* Example,
1920
* Input:
2021
* List1 = 1->3->30->90->120->240->511
2122
* List2 = 0->3->12->32->90->125->240->249
22-
*
23+
* <p/>
2324
* Output: Following is maximum sum linked list out of two input lists
2425
* List = 1->3->12->32->90->125->240->511
25-
*
26+
* <p/>
2627
* NOTE: We switch at 3 and 240 to get above maximum sum linked list
2728
*
2829
* @param node1
@@ -33,19 +34,43 @@ public class MaximumSumLinkedList {
3334
public static <E extends Comparable<E>> SingleLinkedNode<E> maximumSumLinkedList(SingleLinkedNode<E> node1,
3435
SingleLinkedNode<E> node2) {
3536

36-
SingleLinkedNode<E> node = node1, curr1 = node1, curr2 = node2;
37+
boolean isList1 = true;
38+
SingleLinkedNode<E> head = node1, node = node1, curr1 = node1.next, curr2 = node2.next;
3739

3840
while (curr1 != null && curr2 != null) {
39-
40-
41+
if (curr1.item.compareTo(curr2.item) == 0) {
42+
isList1 = !isList1;
43+
}
44+
if (isList1) {
45+
node.next = curr1;
46+
} else {
47+
node.next = curr2;
48+
}
49+
node = node.next;
4150
curr1 = curr1.next;
4251
curr2 = curr2.next;
4352
}
4453

45-
return node;
54+
return head;
4655
}
4756

4857
public static void main(String a[]) {
49-
58+
SingleLinkedList<Integer> linkedList1 = new SingleLinkedList<>();
59+
linkedList1.add(00);
60+
linkedList1.add(11);
61+
linkedList1.add(22);
62+
linkedList1.add(33);
63+
linkedList1.add(44);
64+
linkedList1.add(55);
65+
linkedList1.printList();
66+
SingleLinkedList<Integer> linkedList2 = new SingleLinkedList<>();
67+
linkedList2.add(12);
68+
linkedList2.add(21);
69+
linkedList2.add(26);
70+
linkedList2.add(33);
71+
linkedList2.add(34);
72+
linkedList2.add(67);
73+
linkedList2.printList();
74+
SingleLinkedList.printList(maximumSumLinkedList(linkedList1.head, linkedList2.head));
5075
}
5176
}

0 commit comments

Comments
 (0)