Key to CSE143 Midterm, Autumn 2006 handout #23
1. Method Call Value Returned
------------------------------------------
mystery(8) 8
mystery(74) 11
mystery(-52) 7
mystery(3052) 10
mystery(82534) 22
2. One possible solution appears below.
public void printRange(int x, int y) {
if (x > y) {
throw new IllegalArgumentException();
} else if (x == y) {
System.out.print(x);
} else if (x + 1 == y) {
System.out.print(x + " - " + y);
} else {
System.out.print(x + " > ");
printRange(x + 1, y - 1);
System.out.print(" < " + y);
}
}
3. One possible solution appears below.
public int maxAdjacentPairSum() {
if (front == null || front.next == null)
return 0;
else {
ListNode current = front;
int max = front.data + front.next.data;
while (current.next != null) {
int next = current.data + current.next.data;
if (next > max)
max = next;
current = current.next;
}
return max;
}
}
4. Statement Output
------------------------------------------------------------
var1.method1(); Blue 1/Blue 2
var2.method1(); Green 1
var3.method1(); compiler error
var4.method1(); Green 1
var1.method2(); Blue 2
var2.method2(); Red 2/Blue 2
var3.method2(); compiler error
var4.method2(); Red 2/Blue 2
var1.method3(); compiler error
var2.method3(); Green 3
var3.method3(); compiler error
var4.method3(); compiler error
((Blue)var3).method1(); Blue 1/White 2
((Red)var3).method2(); White 2
((White)var3).method3(); White 3
((White)var4).method3(); runtime error
((Green)var5).method3(); runtime error
((Red)var5).method1(); Blue 1/Red 2/Blue 2
((Blue)var6).method3(); compiler error
((Green)var6).method3(); runtime error
5. One possible solution appears below.
public void switchPairs(Stack s) {
Queue q = new LinkedQueue();
while (!s.isEmpty())
q.enqueue(s.pop());
while (!q.isEmpty())
s.push(q.dequeue());
while (!s.isEmpty())
q.enqueue(s.pop());
while (q.size() > 1) {
int n1 = q.dequeue();
int n2 = q.dequeue();
s.push(n2);
s.push(n1);
}
if (!q.isEmpty())
s.push(q.dequeue());
}
6. One possible solution appears below.
public int maxCount() {
if (size == 0) {
return 0;
} else {
int max = 1;
int count = 1;
for (int i = 1; i < size; i++)
if (elementData[i] == elementData[i - 1]) {
count++;
if (count > max) {
max = count;
}
} else
count = 1;
return max;
}
}
Stuart Reges
Last modified: Fri Sep 16 16:16:07 PDT 2011