CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2002
    Posts
    27

    detecting loops in linked lists

    hello,

    curious on the different algorithms available to detect loops in linked lists.

    One algorithm I heard off was the "Tortouise & Hare" (sp??) where you have two pointers on the list, on of which moves twice as fast. Eventually the two pointers will meet up..

    Are there any other algorithms?

    thanks

    Zameer

  2. #2
    Join Date
    Feb 2001
    Location
    teh INTARWEB
    Posts
    542
    Using 2 iterators, one moving twice as fast as the other, is te most popular technique to do it.

    Another approach can be: If the linked list consists of objects of a class, include a flag bit in the class definition. While traversing, check if the flag bt is already turned on. If it is on, there's a loop. Otherwise, turn it on and continue traversal.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured