/*** * * @author gtowell * File: LinkedList.java * Desc: * An instantiation of a linked list that holds a herd of rabbits */ public class LinkedList implements LinkedListInterface { /** * * @author gtowell * Desc: * Internal class holding nodes in the linked list */ private class Node { /* * The Data contained in the node of the linked list. One rabbit */ public Rabbit data; /** * The next node in the linked list */ public Node next; /** * Constructor for a node * @param data an instance of Rabbit * @param next the node to attach. Typically null. */ public Node(Rabbit data, Node next) { this.data = data; this.next = next; } } /** * the first item in the linked list */ private Node head = null; /** * The last item in the linked list. */ private Node tail = null; /** * The number of items in the linked list */ private int size = 0; /** * @return the number of items in the list */ public int size() {return size;} /** * @return true if the list has no content */ public boolean isEmpty() {return size == 0;} /** * The first rabbit in the list * @return the first rabbit. */ public Rabbit first() { if (isEmpty()) {return null;} else {return head.data;} } /** * The last rabbit in the list * @return the last rabbit */ public Rabbit last() { if (isEmpty()) return null; return tail.data; } /** * A string representation of the entire linked list * @return string representation of the entire linked list */ public String toString() { StringBuffer s = new StringBuffer(); for (Node n=head; n!=null; n=n.next) { s.append( n.data.toString()); if (n != tail) { s.append("\n"); } } return s.toString(); } public void addLast(Rabbit c) { Node newest = new Node(c, null); if (isEmpty()) { head = newest;} else { tail.next=newest; } tail = newest; size++; } public void addFirst(Rabbit c) { Node newest = new Node(c, null); if (isEmpty()) { tail=newest; head=newest; } else { newest.next=head; head=newest; } size++; } public Rabbit removeFirst() { if (isEmpty()) {return null;} Rabbit target = head.data; head = head.next; size--; if (isEmpty()) {tail = null;} return target; } public Rabbit removeLast() { if (isEmpty()) return null; if (head==tail) { Rabbit target=head.data; head=null; tail=null; size=0; return target; } Node prev = null; for (Node n=head; n!=tail; n=n.next) { prev=n; } prev.next=null; Rabbit target = tail.data; tail=prev; size--; return target; } public Rabbit remove(Rabbit r) { if (isEmpty()) {return null;} Node prev=null; Node current = head; while (current !=null && current.data != r) { prev=current; current = current.next; } if (current==null) { return null; } if (current==tail) { tail=prev; prev.next = null; size=size-1; if (size==0) { head=null; } return r; } if (current==head) { return removeFirst(); } prev.next=current.next; size--; return r; } public Rabbit find(String id) { Node curr = head; while (curr!=null) { if (curr.data.getId().equals(id)) { return curr.data; } } return null; } }