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

Commit aa2fc20

Browse files
author
Ram swaroop
committed
maximum sum path: code improved
1 parent 3bdf192 commit aa2fc20

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

src/me/ramswaroop/linkedlists/MaximumSumLinkedList.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,21 @@ public static <E extends Comparable<E>> SingleLinkedNode<E> maximumSumLinkedList
3737
boolean isList1 = true;
3838
SingleLinkedNode<E> head = node1, node = node1, curr1 = node1.next, curr2 = node2.next;
3939

40-
while (curr1 != null && curr2 != null) {
40+
while (curr1 != null || curr2 != null) {
41+
// if either of the list runs out first
42+
if (curr1 == null) {
43+
node.next = curr2;
44+
node = node.next;
45+
curr2 = curr2.next;
46+
continue;
47+
}
48+
if (curr2 == null) {
49+
node.next = curr1;
50+
node = node.next;
51+
curr1 = curr1.next;
52+
continue;
53+
}
54+
4155
if (curr1.item.compareTo(curr2.item) == 0) {
4256
isList1 = !isList1;
4357
}
@@ -70,6 +84,8 @@ public static void main(String a[]) {
7084
linkedList2.add(33);
7185
linkedList2.add(34);
7286
linkedList2.add(67);
87+
linkedList2.add(88);
88+
linkedList2.add(90);
7389
linkedList2.printList();
7490
SingleLinkedList.printList(maximumSumLinkedList(linkedList1.head, linkedList2.head));
7591
}

0 commit comments

Comments
 (0)