1
1
package me .ramswaroop .linkedlists ;
2
2
3
+ import me .ramswaroop .common .SingleLinkedList ;
3
4
import me .ramswaroop .common .SingleLinkedNode ;
4
5
5
6
/**
@@ -14,15 +15,15 @@ public class MaximumSumLinkedList {
14
15
/**
15
16
* Constructs a linked list that contains maximum sum path from start to end
16
17
* from two linked lists starting at {@param node1} and {@param node2}.
17
- *
18
+ * <p/>
18
19
* Example,
19
20
* Input:
20
21
* List1 = 1->3->30->90->120->240->511
21
22
* List2 = 0->3->12->32->90->125->240->249
22
- *
23
+ * <p/>
23
24
* Output: Following is maximum sum linked list out of two input lists
24
25
* List = 1->3->12->32->90->125->240->511
25
- *
26
+ * <p/>
26
27
* NOTE: We switch at 3 and 240 to get above maximum sum linked list
27
28
*
28
29
* @param node1
@@ -33,19 +34,43 @@ public class MaximumSumLinkedList {
33
34
public static <E extends Comparable <E >> SingleLinkedNode <E > maximumSumLinkedList (SingleLinkedNode <E > node1 ,
34
35
SingleLinkedNode <E > node2 ) {
35
36
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 ;
37
39
38
40
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 ;
41
50
curr1 = curr1 .next ;
42
51
curr2 = curr2 .next ;
43
52
}
44
53
45
- return node ;
54
+ return head ;
46
55
}
47
56
48
57
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 ));
50
75
}
51
76
}
0 commit comments