2

I need a LinkedList with a loop in it, and want to manipulate pointers, etc. I was wondering if I could use std::list instead of implementing my own LinkedList class, and use its iterators almost the way I use pointers. But it seems that iterators don't let me do so. This is what I tried to do, which doesn't look right, I know. I'm new to std, please bear with me!

I expect the beginning of the loop to be at node 100.

int main() {
  std::list<int> l = {1, 3, 5, 7, 9, 11, 13, 15, 100, 103, 104, 106};

  std::list<int>::iterator it1 = l.begin();
  while (*it1 != 100) it1 = std::next(it1);

  std::list<int>::iterator it2 = l.begin();
  while (*it2 != 106) it2 = std::next(it2);

  std::next(it2) = it1;  //(106)->next = 100

  std::cout << *(std::next(it2)); //it won't print 100, (obviously?)
}

I think I am completely wrong trying to treat iterators as pointer, but is there absolutely no way I can skip implementing my own LinkedList?

Yalda
  • 680
  • 1
  • 18
  • 39

0 Answers0