Thread: linked list - cycle detection

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    94

    Angry linked list - cycle detection

    I am not looking you to explain the problem with coding... but just let me know what is the problem of cycle detection in linked lists. I read many docs (wikipedia etc.) I cannot understand

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The problem is: "Is there a cycle"? Normally when you think of linked lists, you think of a chain. You start at one end, you follow links forward through the chain, and then you reach the end of the chain so you have a NULL link at the end.

    If you've managed to somehow tie your linked list into a knot, then (say) object #10, instead of pointing to #11 like it should, is pointing instead to #4. So then you have a loop (or a cycle), and if you follow the links you'll just go around and around forever.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    node *fast = head;
    node *slow = head;

    fast = fast->next;
    fast = fast->next;
    slow = slow->next;

    if ( fast == slow ) you have a loop.

    Not forgetting to stop at NULL if you get to the end first.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ Linked list program need help !!!
    By dcoll025 in forum C++ Programming
    Replies: 1
    Last Post: 04-20-2009, 10:03 AM
  2. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  3. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  4. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM