




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





There are six problems each worth five points for a total of 30 points. Show all your work, partial credit will be awarded. When there is not enough room on the test page itself, write in the provided blue books and write and sign your name on each one. No notes, no collaboration.
class ProblemOne { public static void main(String [] args) { MyObjectOne moo = new MyObjectOne() ; moo.addToCounter(5) ; moo.addToCounter(2) ; System.out.println(moo.getCounter()) ; } }
class MyObjectOne { int counter = 0 ; void addToCounter( int numberToAdd ) { // increment counter by numberToAdd counter = counter + numberToAdd ; /* PROBLEM SOLN */ }
int getCounter() { // return the value of counter return counter ; /* THE PROBLEM SOLUTION */ }
class ProblemThree {
private int count = 0 ; private NodeThree root = null ;
void insertAtHead(String s) { NodeThree n = findOnList(s) ; if ( if n!=null ) { // ASSERT n.contents.equals(s)==true // don’t re-insert, adjust count n.count ++ ; /* THE PROBLEM SOLUTION */ } else { // insertAtHead, as Problem Threee // code omitted, assume it’s here } }
NodeThree findOnList(String s) { // returns n such that n.content.equals(s)==true // or null, if no such n exists.
// code omitted, assume it’s here and it works! } }
class NodeThree {
NodeThree next = null ; String content = null ; int count = 1 ;
class ProblemFour { // instance variables and methods as in class ProblemThree
void deleteFromList(String s) { // do the find, if found, check count>0, and if so // decrement count /* PROBLEM SOLUTION START / NodeThree nt = findOnList(s) ; if ( (nt!=null) && (nt.count>0) ) nt.count-- ; / PROBLEM SOLUTION END */ }
ASSERT: (n==null) || (n.count>0)
Discuss how you decided to do all this and produce Java code for the affected methods. Justify why this “lazy deletion” (marking a record as deleted and really deleting it at some later time, when it is more convenient) is just as efficient as non-lazy (immediate) deletion. Solution: Oen approach is to include list clean-up during list search. List print can remain the same, it may be important for debugging to see the zero-count nodes. It depends what the purpose of the print routine is. The result is nearly as efficient as immediate deletion since a deleted node is handled just one extra time, during the search step that truely deletes it.
NodeThree nt = root ; // L.I.: (nt==null) || (nt.count>0) while ( nt!=null ) { // clean-up element following nt in list if ( (nt.next!=null) && (nt.next.count===0) ) nt.next = nt.next.next ; else { // when clean, check nt for find or move on if ( nt.content.equals(s) ) break ; nt = nt.next ; } } return nt ;