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

前端 未结 4 830
长情又很酷
长情又很酷 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:21

    Check out this: Puzzle: Loop in a Linked List

    Pointer Marking: In practice, linked lists are implemented using C structs with at least a pointer; such a struct in C shall be 4-byte aligned. So the least significant two bits are zeros. While traversing the list, you may ‘mark’ a pointer as traversed by flipping the least significant bit. A second traversal is for clearing these bits.

    0 讨论(0)
  • 2021-01-05 17:24

    just remenber where have you been and if you came at same node it is over.

    Try storing entries in binary tree and you have O(N*log(N)) time and O(N) space comlexity

    EDIT

    You can use Log(N) space comlexity if you do not store every but in exponetial order link. That mean that you store 1st, 2nd, 4th, 8th, 16th and then if you get hit you have to continue from that point. Time comlexity for this one is N*Log(n)^2

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 17:34

    The tortoise and hare algorithm can give you both the cycle length and the number of nodes before the cycle begins (λ and μ respectively).

    0 讨论(0)
提交回复
热议问题