Constructive Linked List: Reverse

reverse makes a new linked list whose elements are in the reverse order of the original list; the original is unchanged.


(reverse '(a b c))      ->  (c b a)
This function takes advantage of the fact that cons creates a list in the reverse order of the conses.


(defun reverse (lst)
  (let (answer)
    (setq answer '())
    (while (consp lst)
      (setq answer (cons (first lst) answer))
      (setq lst (rest lst)) )
    answer ))


public static Cons reverse (Cons lst) {
  Cons answer = null;
  while ( consp(lst) ) {
    answer = cons( first(lst), answer );
    lst = rest(lst); }
  return answer; }

Contents    Page-10    Prev    Next    Page+10    Index