Search code examples
c++listc++11cycleforward-list

Can a cycle exist in an std::forward_list?


I'm studying Floyd's Tortoise and Hare algorithm, and trying to model the problem using an std::forward_list. Specifically, I'd like to intentionally create a cycle using an std::forward_list, and detect it with said algo.

(Per comments below, without hacking the interface; that is, use the std::forward_list interface to create the cycle.)

The "problem" is that this doesn't seem to be possible. I've looked at the constructors and mutator methods. As far as I can tell, the interface to std::forward_list prevents such cycles from occurring. This is typically be a good thing, unless you're prepping for an interview, and would like to purposely implement a forward_list with a cycle :^)

Is it possible to create a cycle in an std::forward_list?

References:

How to detect a loop in a linked list?
http://en.cppreference.com/w/cpp/container/forward_list
http://codingfreak.blogspot.com/2012/09/detecting-loop-in-singly-linked-list_22.html


Solution

  • The interface of forward_list (and list, for that matter) is designed specifically to hide the details of nodes and node pointers from the user. They are free from cycles by design and abstraction.

    So no, they do not give you the freedom to create a malformed list. Even using splice doesn't let you do it, as it will remove the items from the old list before putting them in the new one.

    If you want to test a cycle detection algorithm, you'll have to write your own linked list type that allows people to make cycles in it.