LList.java
Select all
/* LList.java David Klick CIS 260 2/2/2005 Implementation of a linked list class where each node holds just an integer. */ public class LList { private class LNode { public int data; public LNode next; public LNode(int val) { next = null; data = val; } } private LNode first = null; private int numElements = 0; public LList() { first = null; numElements = 0; } public void clear() throws MyListException { while (!isEmpty()) removeFirst(); } public LNode addFirst(int n) { LNode ln = new LNode(n); ln.next = first; first = ln; numElements++; return ln; } public LNode addLast(int val) throws MyListException { return add(size(), val); } public LNode add(int val) throws MyListException { return addLast(val); } public LNode add(int ndx, int val) throws MyListException { if (ndx == 0) return addFirst(val); LNode ln = new LNode(val); LNode current = first; LNode previous = null; while ((current != null) && (ndx > 0)) { previous = current; current = current.next; --ndx; } if (ndx > 0) throw new MyListException("Invalid index"); ln.next = current; previous.next = ln; numElements++; return ln; } public int get(int ndx) throws MyListException { if (first == null) throw new MyListException("Empty list"); LNode current = first; while ((current != null) && (ndx > 0)) { current = current.next; --ndx; } if (ndx > 0) throw new MyListException("Invalid index"); return current.data; } public int getFirst() throws MyListException { return get(0); } public int getLast() throws MyListException { return get(size()-1); } public int removeFirst() throws MyListException { return remove(0); } public int removeLast() throws MyListException { return remove(size()-1); } public int remove(int ndx) throws MyListException { if (first == null) throw new MyListException("Empty list"); if (ndx < 0) throw new MyListException("Invalid index specified"); LNode current = first; LNode previous = null; while ((current.next != null) && (ndx > 0)) { previous = current; current = current.next; --ndx; } if (ndx > 0) throw new MyListException("Index not found in list"); int val = current.data; if (current == first) first = current.next; else previous.next = current.next; numElements--; return val; } public boolean isEmpty() { return (numElements == 0); } public int size() { return numElements; } public int indexOf(int val) { int ndx = -1; LNode current = first; while (current != null) { ndx++; if (val == current.data) return ndx; current = current.next; } return -1; } public String toString() { String s = new String(); if (first == null) s += "List is empty"; else { s += "List: "; LNode current = first; s += Integer.toString(current.data); while (current.next != null) { current = current.next; s += ", " + Integer.toString(current.data); } } return s; } } class MyListException extends Exception { public MyListException() {} public MyListException(String msg) { super(msg); } }