Problem #1
CS61B, Fall 1997 Midterm #1 Professor K. Yelick
(2 points) What is y after the following code executes?
static void addOne (int x){
x += 1;
}
int y = 3;
addOne(y);
Answer:
Problem #2
(8 points) Answer questions about the following classes. For parts b-e, choose one of the following:
CE: The code will result in a compiler error from javac.
RT: The code will compile without errors, but will cause an error of some kind run time. OK: The code will compile and run without errors. Show what the program will print.
abstract class A {
abstract public void foo ();
}
class B extends A {
public void foo () { System.out.println(“Calling B.foo”);}
protected int value = 0;
}
class C extends B {
public void foo () { System.out.println(“Calling C.foo,” +
value);}
}
class D extends C {
public void foo () { System.out.println(“Calling D.foo(),” +
value);}
}
a. (2 points)
A a1 = new A();
a1.foo();
CS61B, Fall 1997 Midterm #1 Professor K. Yelick 1
b. (2 points)
A a2 = new B();
a2.foo();
c. (2 points)
A a3 = new C();
a3.foo();
d. (2 points)
B b4 = new D();
((C) b4).foo();
Problem #3
(12 points) Consider the following ListNode class definition.
class ListNode {
int item;
ListNode next;
/** Postcondition: Constructs a new listnode containing i and n
*/
ListNode (int i, ListNode n) { item = i; next = n; }
}
a. (4 Points) Complete the following code to copy a list.
/** Postcondition; returns a copy of l. (Copies all the nodes).
*/
private static ListNode copy(ListNode l) {
if (l == null) return l;
else {
return (new ListNode (_____________ , _____________));
}
}
b. (4 Points) Complete the following code to merge 2 sorted lists.
/** Precondition: ln1 and ln2 are sorted
* Postcondition: returns a new sorted list with all the
elements of ln1 and ln2, modifying ln1 and ln2 in the process. */
Problem #2 2
private static ListNode merge(ListNode ln1, ListNode ln2) {
if (ln1 == null) return (ln2);
if (ln2 == null) return (ln1);
if (ln1.item
int min = s1.pop()
for (int j = 1; j