Count number of nodes in a linked list that may be circular

前端 未结 4 860
长情又很酷
长情又很酷 2021-01-05 17:08

Here is the problem, it is from Sedgwick\'s excellent Algorithms in Java (q 3.54)

Given a link to a node in a singly linked list that contains no null links (i.e. ea

4条回答
  •  佛祖请我去吃肉
    2021-01-05 17:25

    The most elegant solution is Floyd's cycle-finding algorithm: http://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare

    It runs in O(N) time, and only constant amount of memory is required.

提交回复
热议问题