Java Data Structures Linked List
class Link {/*from ww w.j a v a 2 s .c o m*/ public int id; // data item public double data; // data item public Link next; // next link in list public Link(int id, double dd) // constructor { this.id = id; // initialize data data = dd; // ('next' is automatically // set to null) } public void displayLink() // display ourself { System.out.print("{" + id + ", " + data + "} "); } } class LinkList { private Link first; // ref to first link on list public LinkList() { first = null; // no links on list yet } public boolean isEmpty(){ return (first == null); } // insert at start of list public void insertFirst(int id, double dd) { Link newLink = new Link(id, dd); newLink.next = first; first = newLink; } public Link deleteFirst() // delete first item { Link temp = first; first = first.next; return temp; } public void displayList() { System.out.print("List (first-->last): "); Link current = first; // start at beginning of list while (current != null) // until end of list, { current.displayLink(); // print data current = current.next; // move to next link } System.out.println(""); } } public class Main { public static void main(String[] args) { LinkList theList = new LinkList(); theList.insertFirst(2, 2.99); theList.insertFirst(4, 4.99); theList.insertFirst(6, 6.99); theList.insertFirst(8, 8.99); theList.displayList(); while (!theList.isEmpty()) { Link aLink = theList.deleteFirst(); System.out.print("Deleted "); aLink.displayLink(); System.out.println(""); } theList.displayList(); } }