Last Monday in lecture we began our discussion of linked data
structures and reviewed the LinearNode generic class from
Section 4.4 of L&C. Today we will play with a class that uses
LinearNode objects to describe a sled dog team. Here the
class SledDog extends the class Dog from the
midterm, where a SledDog object has an additional
String field called breed and appropriate
get and set methods.
Here is code for LinearNode and some of the code for
the classes Dog, SledDog, and
DogTeam.
public class LinearNode {
private T element;
private LinearNode next;
public LinearNode( ) {next = null; element = null;}
public LinearNode(T elem) {next = null; element = elem;}
public LinearNode getNext( ) {return next;}
public void setNext (LinearNode node) {next = node;}
public T getElement( ) {return element;}
public void setElement (T elem) {element = elem;}
public class Dog {
private String name;
private int age;
// get and set methods, two-parameter constructor omitted
public class SledDog extends Dog {
private String breed = "Husky"; // default only, can be reset
// get and set method, three-parameter constructor omitted
public class DogTeam {
private LinearNode leadNode;
private int size;
// get and set methods, zero-parameter constructor omitted
public boolean isEmpty( ) {return (leadNode == null);}
public void addToLead (SledDog newLead) {
LinearNode newNode = new LinearNode (newLead);
newNode.setNext (leadNode);
leadNode = newNode;
setSize (getSize( ) + 1);}}
Question 1: Write a method public SledDog
removeLead( ) for the DogTeam class that removes
and returns the lead dog. If the team is empty, your method should
return null and not throw an exception. Don't forget to
update the size of the team.
Question 2: Write a method public void
switchLastTwo that will reverse the order of the last two dogs
in the team, if the team has at least two dogs. (If it has zero or
one dog the method should do nothing.)
Question 3: Write a method public SledDog
removeYoungest( ) for the DogTeam class that
removes and returns the dog in the team with the smallest
age, taking the first dog of that age if there are more
than one. If the team is empty, your method should return
null and not throw an exception. Don't forget to update
the size of the team.
Question 4: Write a method public int
countHuskies ( ) for the DogTeam class that
returns the number of dogs in the team whose breed is
exactly "Husky". Remember that the .equals
method of the String class returns whether the parameter
string has the same letters in the same order as the calling string.
Last modified 5 October 2011