I’ve never heard of this joke, but if you want to find a cycle in a linked list, the canonical way to do it is to use two pointers and have one walk one step at a time, while the other walks two. If they are ever equal after they take a step, there’s a cycle. Using signals is – I think it’s safe to say – way over the top. (Unless that’s the joke.)
I’ve heard of the two-pointer approach (with pointer variables typically given the names “tortoise” and “hare”), but I really like the double-free approach.
My Lisp take:
(defun circular-p (list) (setf *print-circle* t) (eql #\# (aref (format nil "~A" list) 0)))
YES 🤣
I’ve never heard of this joke, but if you want to find a cycle in a linked list, the canonical way to do it is to use two pointers and have one walk one step at a time, while the other walks two. If they are ever equal after they take a step, there’s a cycle. Using signals is – I think it’s safe to say – way over the top. (Unless that’s the joke.)
That is the joke. The way I heard it was: keep
free()
ing the nodes, and if there’s a crash (due to double-free) you found a cycle.I’ve heard of the two-pointer approach (with pointer variables typically given the names “tortoise” and “hare”), but I really like the double-free approach.
Of course,
free(x)
could be a noop if you have a garbage collecting C (like Zeta-C)Floyd’s Tortoise and Hare.