//******************************************************************* // // Lab 14 Solution // // MagazineList.java // //******************************************************************* public class MagazineList { private MagazineNode list; //---------------------------------------------------------------- // Sets up an initially empty list of magazines. //---------------------------------------------------------------- public MagazineList() { list = null; } //---------------------------------------------------------------- // Creates a new MagazineNode object and adds it to the end of // the linked list. //---------------------------------------------------------------- public void addBack (Magazine mag) { MagazineNode node = new MagazineNode (mag); MagazineNode current; if (list == null) list = node; else { current = list; while (current.next != null) current = current.next; current.next = node; } } //---------------------------------------------------------------- // Creates a new MagazineNode object and adds it to the front of // the linked list. //---------------------------------------------------------------- public void addFront (Magazine mag) { MagazineNode node = new MagazineNode (mag); node.next = list; list = node; } //---------------------------------------------------------------- // Removes the first MagazineNode from the linked list and returs // the Magazine object. Return null if list is empty; //---------------------------------------------------------------- public Magazine removeFront() { if (list == null) return null; else { Magazine mag = list.magazine; list = list.next; return mag; } } //---------------------------------------------------------------- // Returns the number of Magazine nodes in the linked list //---------------------------------------------------------------- public int count() { MagazineNode current = list; int count = 0; while (current != null) { count++; current = current.next; } return count; } //---------------------------------------------------------------- // Returns this list of magazines as a string. //---------------------------------------------------------------- public String toString () { String result = ""; MagazineNode current = list; if (current == null) return ("\n\nThe list is empty."); else while (current != null) { result += current.magazine + "\n"; current = current.next; } return result; } //***************************************************************** // An inner class that represents a node in the magazine list. // The public variables are accessed by the MagazineList class. //***************************************************************** private class MagazineNode { public Magazine magazine; public MagazineNode next; //-------------------------------------------------------------- // Sets up the node //-------------------------------------------------------------- public MagazineNode (Magazine mag) { magazine = mag; next = null; } } }