// Demonstrate some list building code public class BuildLists { // Given a list of Psersons construct the corresponding list of names. // Iterative solution // public static MyList PersonL2Names(MyList pl) { if (pl == null) return null; MyList first = new MyList(); MyList last = first; while (pl != null) { last.setValue(pl.getValue().getFirstName()); if (pl.getNext() == null) return first; MyList n = new MyList(); last.setNext(n); last = n; pl = pl.getNext(); } return first; } // Given a list of Psersons construct the corresponding list of names. // Recursive solution // public static MyList PersonL2NamesB(MyList pl) { if (pl == null) return null; MyList first = new MyList(); first.setValue(pl.getValue().getFirstName()); first.setNext(PersonL2NamesB(pl.getNext())); return first; } // From the list of Persons pl, destructively delte all persons of sex // s // // pl is a variable that works its way down the list // 3 is used to find the next Person not of sex s after pl. // public static MyList deleteSex(MyList pl, Sexes s) { MyList d = pl; MyList willReturn = null; while (pl != null && pl.getNext() != null) { d = pl.getNext(); while (d != null && d.getValue().getSex() == s) // Find the next person not of sex s d = d.getNext(); pl.setNext(d); if (willReturn == null) // at the end, return the first element of if (pl.getValue().getSex() != s) // the list, if that is the right willReturn = pl; // sex else willReturn = d; // else return the first Person of tright sex pl = d; // move pl up to d; } return willReturn; } public static void main(String args[]) { Person BarackObama= new Person("Barack", "Obama", Sexes.Male); Person MichelleObama= new Person("Michelle", "Obama", Sexes.Female); Person MaliaObama= new Person("Malia", "Obama", Sexes.Female); Person SashaObama= new Person("Sasha", "Obama", Sexes.Female); Person AnnDunham= new Person("Ann", "Dunham", Sexes.Female); Person BarackObamaSr= new Person("Barack", "Obama", Sexes.Male); BarackObama.setParent(AnnDunham); BarackObama.setParent(BarackObamaSr); MaliaObama.setParent(BarackObama); MaliaObama.setParent(MichelleObama); SashaObama.setParent(BarackObama); SashaObama.setParent(MichelleObama); MyList osr = new MyList(); MyList ann = new MyList(); MyList oba = new MyList(); MyList mic = new MyList(); MyList mal = new MyList(); MyList sas = new MyList(); osr.setValue(BarackObamaSr); ann.setValue(AnnDunham); oba.setValue(BarackObama); mic.setValue(MichelleObama); mal.setValue(MaliaObama); sas.setValue(SashaObama); osr.setNext(ann); ann.setNext(oba); oba.setNext(mic); mic.setNext(mal); mal.setNext(sas); System.out.println(osr.toString()); MyList women = deleteSex(osr,Sexes.Male); System.out.println(women.toString()); } // end main } // end BuildLists