Constructing a Linked List

A linked list is usually made by linking new elements onto the front of the list. In Lisp, the system function (cons item list ) makes a new list element containing item and adds it to the front of list:


(cons 'a nil)              ->  (a)
cons("a", null)

(cons 'a '())              ->  (a)

(cons 'a '(b c))           ->  (a b c)
cons("a", list("b", "c"))

We can easily do the same thing in Java:


public class Cons  {
    private Object car;
    private Cons cdr;

    private Cons(Object first, Cons rest)
       { car = first;
         cdr = rest; }
    public static Cons
                  cons(Object first, Cons rest)
      { return new Cons(first, rest); }

Contents    Page-10    Prev    Next    Page+10    Index