package CIS115.linkedlist; public class BookList { public BookNode head; public BookNode tail; // add a book to the list public void add(Book b) { // new node holds the book BookNode node = new BookNode(); node.contents = b; // special case for first node if (head == null) { head = node; tail = node; } else { // add the new node at end and update tail tail.next = node; tail = node; } } // print the whole list public void printList() { // start at head BookNode current = head; System.out.println("List Begins"); int i = 0; // for readability of output // keep going through whole list while(current != null) { System.out.println(i + ". " + current.contents); // move down one node current = current.next; i++; } System.out.println("List Ends"); } // remove and return book at position pos (counting from 0) public Book remove (int pos) { // current node we are looking at BookNode current = head; // used to store one node back so we can splice out BookNode prev = null; // to store the book we're removing Book result = null; // loop to find the position, stop if we run out of nodes // could use while instead, either way we need && // could go 0 to < pos, but this is more readable "stop at pos" // since current started at head already for (int i = 1; i <= pos && current != null; i++) { prev = current; // chase current current = current.next; } // if we found that position if (current != null) { result = current.contents; // special case for first node, need to update head if (current == head) { head = head.next; } else { // special case for last node, need to update tail if (current == tail) { tail = prev; } // splice out the current node prev.next = current.next; } } return result; } }