0

So, I've been wondering if there is a way to create a circular linked list with std::list in c++. I can't seem to figure out a way to get the last element to point to the first. Any ideas how someone could do that?

  • 2
    You can't force a `std::list` to act this way, but you can wrap it with something that will. (`boost::iterator_adapator` could be very useful.) – aschepler Jul 10 '20 at 11:42
  • With `std::list` you don't get to control the links. So you can't. – user253751 Jul 10 '20 at 11:42
  • you might find your answer here https://stackoverflow.com/questions/947489/does-a-standard-implementation-of-a-circular-list-exist-for-c – Mustafa Reda Jul 10 '20 at 11:44

2 Answers2

2

std::list interface doesn't support a circular list where first.prev is a pointer to last, and last.next is a pointer to first.

You can't decrement the iterator returned by std::list::begin(). More generally, you can't decrement any iterator returned by std:: ... ::begin().

Incrementing the iterator returned by std::list::back() results in an iterator == std::list::end() (the same is true in general for std:: ... :: back()).


If you're curious, Visual Studio template implements std::list internally using a dummy node as part of a circular doubly linked list. dummy.next points to first, dummy.prev points to last, and first.prev == last.next == pointer to dummy node, but this doesn't allow you to treat this as a conventional circular doubly linked list.

rcgldr
  • 27,407
  • 3
  • 36
  • 61
1

No, there is not.

std::list does not allow you to control the links yourself. The list controls the links for you. You cannot customize them.

Note that if you could customize the links in the list, the functions in the list would probably not work correctly. For example, if you iterated over a circular list, you'd never finish!

user253751
  • 57,427
  • 7
  • 48
  • 90
  • one can write a circular list backed up by a `std::list`, also the fact that a circular list has no `end` is not specific to implementing a circular list with `std::list`, its just what makes a circular list circular – 463035818_is_not_an_ai Jul 10 '20 at 12:09
  • @idclev463035818 If you used the same code designed for a non-circular list with a circular list, it might never finish iterating. – user253751 Jul 10 '20 at 14:18