Key to Sample CSE143 Midterm, Autumn 2007 handout #21
1. Method Call Output Produced
-----------------------------------------------
mystery(1); 1
mystery(3); 3, 10, 5, 16, 8, 4, 2, 1
mystery(4); 4, 2, 1
mystery(5); 5, 16, 8, 4, 2, 1
mystery(20); 20, 10, 5, 16, 8, 4, 2, 1
2. One possible solution appears below.
public int evens(int n) {
if (n < 0)
return -evens(-n);
else if (n == 0)
return 0;
else if (n % 2 == 0)
return 10 * evens(n / 10) + n % 10;
else
return evens(n / 10);
}
3. One possible solution appears below.
public void printInversions() {
ListNode current = front;
while (current != null) {
ListNode current2 = current;
while (current2 != null) {
if (current.data > current2.data)
System.out.println("(" + current.data + ", "
+ current2.data + ")");
current2 = current2.next;
}
current = current.next;
}
}
4. Statement Output
------------------------------------------------------------
var1.method1(); Milk 1/Fruit 3/Milk 3
var2.method1(); Milk 1/Juice 3
var3.method1(); Milk 1/Egg 3
var4.method1(); Milk 1/Juice 3
var5.method1(); Milk 1/Milk 3
var6.method1(); compiler error
var1.method2(); compiler error
var2.method2(); Juice 2/Fruit 3/Milk 3
var3.method2(); compiler error
var1.method3(); Fruit 3/Milk 3
var2.method3(); Juice 3
var3.method3(); Egg 3
((Juice)var6).method1(); runtime error
((Fruit)var1).method1(); Milk 1/Fruit 3/Milk 3
((Fruit)var3).method2(); compiler error
((Fruit)var4).method1(); Milk 1/Juice 3
((Juice)var3).method2(); runtime error
((Egg)var3).method2(); Egg 2
((Fruit)var4).method3(); Juice 3
((Milk)var6).method3(); Fruit 3/Milk 3
5. One possible solution appears below.
public void shift(Stack s, int n) {
if (n < 0 || n > s.size())
throw new IllegalArgumentException();
Queue q = new LinkedQueue();
int otherSize = s.size() - n;
for (int i = 0; i < otherSize; i++)
q.enqueue(s.pop());
while (!q.isEmpty())
s.push(q.dequeue());
while (!s.isEmpty())
q.enqueue(s.pop());
while (!q.isEmpty())
s.push(q.dequeue());
}
6. One possible solution appears below.
public void removeFront(int n) {
if (n < 0 || n > size)
throw new IllegalArgumentException();
for (int i = n; i < size; i++)
elementData[i - n] = elementData[i];
size -= n;
}
Stuart Reges
Last modified: Fri Sep 16 16:16:07 PDT 2011