Contents    Page-10    Prev    Next    Page+10    Index   

Two Pointer Queue using Linked List

A linked list makes a good queue if we keep a pointer to the end of the list as well as the front.


public class MyQueue {
    private Cons front;
    private Cons end;
    public MyQueue() { front = null; }

    public MyQueue insert(Object val) {
      Cons element = Cons.list(val);
      if ( front == null )
         front = element;
        else Cons.setrest(end, element);
      end = element;
      return this; }

    public Object remove () {       // same as pop
        Object val = Cons.first(front);
        front = Cons.rest(front);
        return val; }