This preview shows pages 1–3. Sign up to view the full content.

Answers to Self-Study Questions Test Yourself #1 Test Yourself #2 Question 1: l.getNext().setData("cat"); Question 2: l.setNext(new Listnode<String>("rat", l.getNext())); Test Yourself #3 The list begins: and after the code looks like: Page 1 of 5 Linked-list Answers 2008/3/27 http://pages.cs.wisc.edu/~cs367-1/topics/Linked-Lists/answers.html

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
and this is correct. Test Yourself #4 Here's the code for the add method that adds to the end of the list. //********************************************************************** // add // // Given: Object ob // // Do: Add ob to the end of the list // // Implementation: // o create a new Listnode for ob, pointed to by the "next" field // of the last node in the list (which will be the header node if // the list is empty) // o change the lastNode pointer to point to the new node // o increment numItems. // //********************************************************************** public void add(E ob) { lastNode.setNext(new Listnode<E>(ob)); lastNode = lastNode.getNext(); numItems++; } Test Yourself #4a //********************************************************************** // get // // Given: int pos and // // Do: Throw an exception if pos has a bad value. // Otherwise, return the data at the given pos (counting from zero) // // Implementation: // Check for a bad position and if so, throw an exception. // Otherwise: // // o find the node n in position pos (counting the header // node as being in position -1) // // o return the data in that node // //********************************************************************** public E get(int pos) { // check for bad position if (pos < 0 || pos > numItems) {
This is the end of the preview. Sign up to access the rest of the document.