CS307 Fall 2004 Midterm 2 Suggested Solutions 1. Short answer questions. Answer as below or -2. On Big O okay if leave off the O() A. 12 B. *1 2 3 4 C. 45 D. O(N) E. O(log N) F. O(1) G. O(N^2) H. O(N + M) //O(N) or O(M) okay as well I. O(N^2) J. 15 sec K. 24 sec L. 104 sec. (fractions okay, no terms with log allowed) M. 5 6 7 8 9 N. 13 2 5 11 O. 9 4 4 1 8 0 2. Set result = new Set(); for(int i = 0; i < myCon.size(); i++) if( !otherSet.myCon.contains( myCon.get(i) ) result.myCon.add( myCon.get(i) ); return result; 3. boolean result; // other list empty? if so this contains all if( other.myHead == null ) result = true; else { SortableNode thisTemp = myHead; SortableNode otherTemp = other.myHead; int res; while( thisTemp != null && otherTemp != null ) { res = otherTemp.getData().compareTo( thisTemp.getData() ); //current data in other larger than data in this if( res > 0 ) thisTemp = thisTemp.getNext(); //if == advance otherTemp (allow double counting if necessary) //if ensuring one for one I would advance both pointers else if( res == 0 ) otherTemp = otherTemp.getNext(); // current data in other smaller (!) than data in this // because sorted it will not be present and we can stop else thisTemp = null; } //had to "fall off" other to have counted them all. result = otherTemp = null; } return result; 4. return distHelper(myHead, 0); private int distHelper(Node cur, int distSoFar) { int result; //found it? if( cur == myTail ) result = distSoFar; //fell off? if so send back flag to indicate dead end else if( curr == null ) result = -1; else { //check next and add 1 for moving forward result = distHelper( cur.getNext(), distSoFar + 1); // Did that lead to a dead end? // If so check the data node and if it is a Node, try it if( result == -1 && cur.getData() instanceof Node) result = distHelper( (Node)cur.getData(), distSoFar + 1); } return result; }