Iterative Append

An iterative version of append can copy the first list in a loop, using O(1) stack space. For this function, it is convenient to use the setrest function:


public static Cons append (Cons x, Cons y) {
        Cons front = null;
        Cons back = null;
        Cons cell;
        if ( x == null ) return y;
        for ( ; x != null ; x = rest(x) ) {
             cell = cons(first(x), null);
             if ( front == null )
                 front = cell;
             else setrest(back, cell);
             back = cell; }
        setrest(back, y);
        return front; }     

Contents    Page-10    Prev    Next    Page+10    Index