diff --git a/src/Exercises.java b/src/Exercises.java index 0da86bf..bd5a865 100644 --- a/src/Exercises.java +++ b/src/Exercises.java @@ -12,7 +12,14 @@ public class Exercises { * @return sum of the values in the list */ public static int sum(ListNode head) { - return -1; + int total = 0; + + while(head != null){ + total += head.data; + head = head.next; + } + + return total; } /** @@ -28,7 +35,16 @@ public static int sum(ListNode head) { * @return a count of the negative values in the list */ public static int countNegative(ListNode head) { - return -1; + + int count = 0; + + while(head != null){ + if(head.data < 0){ + count++; + } + head = head.next; + } + return count; } /** @@ -46,6 +62,16 @@ public static int countNegative(ListNode head) { * @param toAdd the value to append in a new node */ public static void addToEnd(ListNode head, int toAdd) { + if (head == null){ + return; + } + + ListNode current = head; + while (current.next != null){ + current = current.next; + } + + current.next = new ListNode(toAdd); } @@ -63,6 +89,18 @@ public static void addToEnd(ListNode head, int toAdd) { */ public static void makePositive(ListNode head) { + if (head == null){ + return; + } + + ListNode current = head; + while(current != null){ + if(current.data < 0){ + current.data = -current.data; + } + current = current.next; + } + } /** @@ -82,6 +120,19 @@ public static void makePositive(ListNode head) { * @return whether the list is increasing */ public static boolean isIncreasing(ListNode head) { - return false; + + if (head == null || head.next == null){ + return true; + } + + ListNode current = head; + + while(current.next != null){ + if(current.data > current.next.data){ + return false; + } + current = current.next; + } + return true; } }