Home > OS >  How do I link different nodes of an std::list?
How do I link different nodes of an std::list?

Time:06-13

If I have an std::list of size 6 (contains 6 elements). I want to take the front node, disconnect it from the second node so that the second node becomes the front/head), and attach the original front node to the back so that the front node is now the back() or tail. In plainer language, I want to remove the node from the front and attach it to the back. However remove() function is iterative function that searches the entire container, and erase() destroys the actual node itself, which will mean deallocation of memory. I just want to disconnect the node and reattach it to the back. Can this be done? Also can this be done to insert at a random point in the linked list (like in the middle)?

CodePudding user response:

Use std::list::splice:

#include <iostream>
#include <iterator>
#include <list>

int main()
{
    std::list<int> x = {1,2,3,4,5,6};

    x.splice(x.end(), x, x.begin());

    for (int elem : x)
        std::cout << ' ' << elem;
    std::cout << '\n';

    // Prints 2 3 4 5 6 1
}
  •  Tags:  
  • c
  • Related