Contents    Page-10    Prev    Next    Page+10    Index   

Sentinel Node

The push and pop operations on a stack both have side effects on the pointer to the stack. If that pointer is a variable, we cannot write push and pop as subroutines. A common technique is to put an extra dummy node or sentinel at the front of the list; the sentinel node points to the actual list. Then we can write subroutines:

public static Cons
          pushb (Cons sentinel, Object item) {
  setrest(sentinel, cons(item,rest(sentinel)));
  return sentinel; }

public static Object popb (Cons sentinel) {
  Object item = first(rest(sentinel));
  setrest(sentinel, rest(rest(sentinel)));
  return item; }

(defun pushb (sentinel item)
  (setf (rest sentinel)
        (cons item (rest sentinel)) )
  sentinel )

(defun popb (sentinel)
  (let (item)
    (setq item (first (rest sentinel)))
    (setf (rest sentinel) (rest (rest sentinel)))
    item ))