Hacker News new | past | comments | ask | show | jobs | submit login

The way I thought of immediately uses 0 pointers:

  (defun nthFromEnd (lst n)
    (labels ((from-end-helper (lst n)
      (if (null lst)
        0
        (let ((ret (from-end-helper (cdr lst) n)))
          (if (eq ret n)
            (throw 'answer (car lst))
            (+ ret 1))))))
      (catch 'answer
        (when (from-end-helper lst n)
          nil))))

  CL-USER> (nthfromend '(1 2 3 4 5) 6)
  NIL
  CL-USER> (nthfromend '(1 2 3 4 5) 3)
  2
  CL-USER> (nthfromend '(1 2 3 4 5) 0)
  5
I didn't hammer it very hard so maybe I missed a case or two. The other obvious problem is that it's not tail recursive (nor very elegant in general)



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: