Professional Documents
Culture Documents
Problem Set 3, Part I Problem 1: Printing The Odd Values in A List of Integers
Problem Set 3, Part I Problem 1: Printing The Odd Values in A List of Integers
Problem Set 3, Part I Problem 1: Printing The Odd Values in A List of Integers
2-2)
I assume fairly consistent means that we can use an ArrayList because the size
is fixed, however in real life I would still use LLList because I am paranoid.
Also I wrote too much for the above answer, but the characteristics for each
data structure that I wrote in the above answer also apply here.
2-3)
‘Very few additions or removals’ means we can use an ArrayList because size
should be relatively fixed. ‘frequently access the item’ is a deal breaker for
the LLList because that sounds like random access. LLList is O(n) in random
access while ArrayList is O(1).
ps: if we had the ArrayList from the java standard library I would use it for
everything because a linked list sucks, I only use a linked list in haskell
3-2)
public static LLList reverse(LLList list) { LLList rev = new LLList();
ListIterator iter = list.iterator(); while (iter.hasNext()) { Object item =
iter.next(); rev.addItem(item, 0); } return rev; }
3-3)
The worst-case running time of the improved algorithm is O(n). This is because
all the function does is traverse the linked list and update the variable that
contains a pointer to the head of the list. Since we are always adding to the
beginning of the list, it is O(1) for each addition.
Problem 4: Removing a value from a doubly-linked list
public static DNode remAll(DNode node, char c) { DNode head = node; for (DNode
trav = node; trav != null;) { if (trav.ch == c) { if (trav.prev == null) {
DNode next = trav.next; trav.next.prev = null; trav.next = null; trav = next;
head = next; continue; } DNode next = trav.next; trav.prev.next = trav.next;
trav.next.prev = trav.prev; trav.next = null; trav.prev = null; trav = next;
continue; } trav = trav.next; } return head; }