Queue.java

jmud-0.11/src/util/list/Queue.java · 1.6 KB

From the archive jmud-0_11.tgz

Download the archive   « Back to the archive contents

package util.list;

import java.util.NoSuchElementException;

public class Queue extends List {

  private ListLink tail = null;

  public Queue() {
  }

  private void add(ListLink aLink) {
    if (tail != null)
      tail.setNext(aLink);
    tail = aLink;
    if (head == null)
      head = tail;
  }

  public void insert(Object info) {
    add(new ListLink(info, null));
  }

  ListLink getTail() {
    return tail;
  }

  void setTail(ListLink t) {
    tail = t;
  }

  private ListLink findLastLink() {
    if (head == null)
      return null;

    ListLink curr = head;

    while (curr.getNext() != null)
      curr = curr.getNext();

    return curr;
  }

  public void remove(Object info) throws NoSuchElementException {
    super.remove(info);

    if (head == null)
      tail = null;
    else if (tail.getInfo() == info) 
      tail = findLastLink();
  }

  public Object remove() throws NoSuchElementException {
    if (head == null)
      throw new NoSuchElementException();

    Object info = head.getInfo();
    head = head.getNext();

    if (head == null)
      tail = null;

    return info;
  }

  public Object clone() {

    Queue cloneQueue = new Queue();
    ListEnumeration myElements = elements();

    if (myElements.hasMoreElements()) {

      ListLink prevLink = new ListLink(myElements.nextElement(), null);
      cloneQueue.add(prevLink);

      while (myElements.hasMoreElements()) {
	prevLink.setNext(new ListLink(myElements.nextElement(), null));
	prevLink = prevLink.getNext();
      }

    }

    return cloneQueue;
  }

  public Iterator getIterator() {
    return new QueueIterator(this);
  }
}


Site Stats

Snippets: 1791
Codebases: 571