Key to CSE143 Midterm, Fall 2011 handout #24
1. Method Call Output Produced
------------------------------------------------
mystery(3); 3
mystery(42); 242
mystery(293); 39293
mystery(402); 20402
mystery(2468); 8642468
2. One possible solution appears below.
public void writeNumbers(int n) {
if (n < 1)
throw new IllegalArgumentException();
else if (n == 1)
System.out.print(1);
else if (n % 2 == 1) {
System.out.print(n + ", ");
writeNumbers(n - 1);
} else {
writeNumbers(n - 1);
System.out.print(", " + n);
}
}
3. One possible solution appears below.
public boolean increasingTriples() {
ListNode current = front;
while (current != null && current.next != null &&
current.next.next != null) {
if (current.data >= current.next.data ||
current.next.data >= current.next.next.data)
return false;
current = current.next.next.next;
}
if (current!= null && current.next != null &&
current.data >= current.next.data)
return false;
return true;
}
4. Statement Output
------------------------------------------------------------
var1.method1(); Scoop 1
var2.method1(); Spoon 1/Cone 1
var3.method1(); Cone 1
var4.method1(); compiler error
var5.method1(); Scoop 1
var6.method1(); compiler error
var1.method2(); Cone 2/Scoop 1
var2.method2(); Cone 2/Spoon 1/Cone 1
var3.method2(); Cone 2/Cone 1
var4.method2(); compiler error
var5.method2(); Cone 2/Scoop 1
var6.method2(); compiler error
((Spoon)var1).method3(); compiler error
((Cup)var6).method3(); Cup 3
((Scoop)var4).method1(); runtime error
((Cone)var6).method2(); Cone 2/Cone 1
((Cone)var4).method1(); Spoon 1/Cone 1
((Scoop)var6).method3(); runtime error
((Scoop)var3).method3(); runtime error
((Scoop)var5).method3(); Scoop 3
5. One possible solution appears below.
public boolean isConsecutive(Stack s) {
if (s.size() <= 1)
return true;
else {
Queue q = new LinkedList();
int prev = s.pop();
q.add(prev);
boolean ok = true;
while (!s.isEmpty()) {
int next = s.pop();
if (prev - next != 1)
ok = false;
q.add(next);
prev = next;
}
while (!q.isEmpty())
s.push(q.remove());
while (!s.isEmpty())
q.add(s.pop());
while (!q.isEmpty())
s.push(q.remove());
return ok;
}
}
6. One possible solution appears below.
public void insertAt(int index, int n, int value) {
if (index < 0 || index > size || n < 0)
throw new IllegalArgumentException();
for (int i = size - 1; i >= index; i--)
elementData[i + n] = elementData[i];
for (int i = 0; i < n; i++)
elementData[i + index] = value;
size += n;
}
Stuart Reges
Last modified: Fri Sep 16 16:16:07 PDT 2011