{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

homework4_001

# homework4_001 - 15-121 FALL 2009[CORTINA HOMEWORK 4 due...

This preview shows pages 1–5. Sign up to view the full content.

15-121 FALL 2009 [CORTINA] HOMEWORK 4 - due Wednesday, September 30 by 11:59PM ELECTRONIC HANDIN AVAILABLE THURS AFTER 5 PM PROBLEMS (10 points) 1.(2 pts) Write a method that reverses the order of elements in an ArrayList<E> without creating a new ArrayList . You may only use the methods remove , add , and size . 2.(1.5 pt) The following method is supposed to remove all duplicates from an ArrayList of Integer : public static void removeDuplicates(ArrayList<Integer> list) { int numValues = list.size(); for (int i = 0; i < numValues-1; i++) { for (int j = i+1; j < numValues; j++) { if (list.get(i) == list.get(j)) list.remove(j); } } } 3.Clearly identify all logical errors in this implementation.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4.Derive the worst-case runtime complexity of this algorithm in big-O notation if the list has n integers in it. When does this worst-case occur? 5.(1.5 pts) A singly linked list of integers is shown below. _ ------- ------- ------- -------- | | | | | | | | | | | | | | head |----->| 4 | ---->| 7 | ---->| 2 | ---->| 6 |null| |_| | | | | | | | | | | | | ------- ------- ------- -------- 6.What does the following code fragment output for the list above? What does it output in general? int s = 0; Node p = head; while (p != null) { s += p.data; p = p.next; } System.out.println(s); 7.What does the following code fragment output for the list above? What does it output in general? What must be true about this list to avoid a runtime error? int s = 0; Node p = head; while (p.next != null) { s += p.data; p = p.next; } System.out.println(s); 8.What is wrong with the following code?
int s = 0; while (head != null) { s += head.data; head = head.next; } System.out.println(s); 9.(1.5 pts) Consider the SinglyLinkedList class discussed in lecture. 10.Write a method length for this class that returns the number of elements in the list by traversing the list. Do not use the numElements field or the size method in your solution. 11.What is the runtime complexity of your solution in big-O notation if the list has n elements? How does this compare to the runtime complexity of the size method we discussed in lecture?

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
12.(2 pts) Consider the SinglyLinkedList class discussed in lecture. Write a method addToHead that takes an element of type E and attaches it at the head of the linked list only if it is not already in the list. Do not use any
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}