Create a Queue Implemented by a Linked List in Java

Description

The following code shows how to create a Queue Implemented by a Linked List.

Example


class Link {/* ww w .j  a  v a  2s.  c  o  m*/
  public int iData;
  public Link next;
  public Link(int id) {
    iData = id;
  }

  public String toString() {
    return "{" + iData + "} ";
  }
}

class LinkList {
  private Link first;

  public LinkList() {
    first = null;
  }

  public boolean isEmpty() {
    return (first == null);
  }

  public void insertFirst(int dd) {
    Link newLink = new Link(dd);
    newLink.next = first;
    first = newLink;
  }

  public int deleteFirst() {
    Link temp = first;
    first = first.next;
    return temp.iData;
  }

  public String toString() {
    String str = "";
    Link current = first;
    while (current != null) {
      str += current.toString();
      current = current.next;
    }
    return str;
  }
}

class FirstLastList {
  private Link first;

  private Link last;

  public FirstLastList() {
    first = null;
    last = null;
  }

  public boolean isEmpty() {
    return first == null;
  }

  public void insertFirst(int dd) {
    Link newLink = new Link(dd);
    if (isEmpty())
      last = newLink;
    newLink.next = first;
    first = newLink;
  }

  public void insertLast(int dd) {
    Link newLink = new Link(dd);

    if (isEmpty())
      first = newLink;
    else
      last.next = newLink;
    last = newLink;
  }

  public int deleteFirst() {
    int temp = first.iData;
    if (first.next == null)
      last = null;
    first = first.next;
    return temp;
  }

  public String toString() {
    String str = "";
    Link current = first;
    while (current != null) {
      str += current.toString();
      current = current.next;
    }
    return str;
  }
}

class LinkQueue {
  private FirstLastList theList;

  public LinkQueue() {
    theList = new FirstLastList();
  }

  public boolean isEmpty() {
    return theList.isEmpty();
  }

  public void insert(int j) {
    theList.insertLast(j);
  }

  public double remove() {
    return theList.deleteFirst();
  }

  public String toString() {
    return theList.toString();
  }
} 

public class Main {
  public static void main(String[] args) {
    LinkQueue theQueue = new LinkQueue();
    theQueue.insert(20);
    theQueue.insert(40);
    System.out.println(theQueue);

    theQueue.insert(60);
    theQueue.insert(80);

    System.out.println(theQueue);

    theQueue.remove();
    theQueue.remove();

    System.out.println(theQueue);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet