publicvoidaddFirst(int x) { first = newIntNode(x, first); } }
1.1 Implement SLList.insert which takes in an integer x and inserts it at the given position. If the position is after the end of the list, insert the new node at the end. For example, if the SLList is 5 → 6 → 2, insert(10, 1) results in 5 → 10 → 6 → 2.
1 2 3 4 5 6 7 8 9 10 11 12 13
publicvoidinsert(int item, int position) { if (first == null || position == 0) { addFirst(item); return; } IntNodep= first; inti=1; while (i < position && p.next != null) { p = p.next; i++; } p.next = newIntNode(item, p.next); }
1.2 Add another method to the SLList class that reverses the elements. Do this using the existing IntNodes (you should not use new).
1 2 3 4 5 6 7 8 9 10 11 12 13
// Iteratively reverse, using prev, curr and next pointer publicvoidreverse() { IntNodeprevNode=null; IntNodecurrNode= first; IntNodenextNode=null; while (currNode != null) { nextNode = currNode.next; currNode.next = prevNode; prevNode = currNode; currNode = nextNode; } first = prevNode; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// recursively reverse sllist, first traverse the list then go back while setting the direction reversed. publicvoidreverse() { first = reverseRecursiveHelper(first); }
2.1 Consider a method that inserts item into array arr at the given position. The method should return the resulting array. For example, if x = [5, 9, 14, 15], item = 6, and position = 2, then the method should return [5, 9, 6, 14, 15]. If position is past the end of the array, insert item at the end of the array. Is it possible to write a version of this method that returns void and changes arr in place (i.e., destructively)? Extra: Write the described method:
1 2 3 4 5 6 7 8 9 10 11 12
publicstaticint[] insert(int[] arr, int item, int position) { int[] res = newint[arr.length + 1]; position = Math.min(arr.length, position); for (inti=0; i < position; i++) { res[i] = arr[i]; } res[position] = item; for (inti= position, i < arr.length; i++) { res[i + 1] = arr[i]; } return res; }
Consider a method that destructively reverses the items in arr. For example calling reverse on an array [1, 2, 3] should change the array to be [3, 2, 1]. What is the fewest number of iteration steps you need? What is the fewest number of additional variables you need? Extra: Write the method:
Extra: Write a non-destructive method replicate(int[] arr) that replaces the number at index i with arr[i] copies of itself. For example, replicate([3, 2, 1]) would return [3, 3, 3, 2, 2, 1].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicstaticint[] replicate(int[] arr) { inttotal=0; for (int item : arr) { total += item; } inti=0; int[] res = newint[total]; for (int item : arr) { for (intcounter=0; counter < item; counter++) { res[i] = item; i++; } } return res; }