/* LinkedList.java CIS 260 2014-03-11 David Klick Implementation of a linked list with generics. */ import java.util.NoSuchElementException; public class LinkedList { private class Node { T data; Node next; } private Node head; public LinkedList() { head = null; } public int length() { int count = 0; Node p = head; while (p != null) { count++; p = p.next; } return count; } @Override public String toString() { String out = ""; Node p = head; while (p != null) { out += p.data; p = p.next; } return out; } public T front() { if (head == null) throw new NoSuchElementException(); return head.data; } public T back() { Node current = head; if (head == null) throw new NoSuchElementException(); while (current.next != null) current = current.next; return current.data; } public T get(int ndx) { if (ndx < 0) throw new NoSuchElementException(); int temp = 0; Node current = head; while (temp < ndx) { if (current == null) throw new NoSuchElementException(); if (ndx == temp) return current.data; current = current.next; temp++; } if (current == null) throw new NoSuchElementException(); return current.data; } public boolean isEmpty() { return (head == null); } public void add(T data) { Node current = head; Node p = new Node(); p.data = data; p.next = null; if (head == null) { head = p; } else { while (current.next != null) current = current.next; current.next = p; } } public boolean remove(T data) { if (head == null) return false; if (head.data.equals(data)) { head = head.next; return true; } Node prev = head; Node curr = prev.next; while (curr != null) { if (curr.data.equals(data)) { prev.next = curr.next; return true; } else { prev = curr; curr = prev.next; } } return false; } }