I was told that something could be done like that, but it’s confusing, I don’t quite understand:

struct Node{ int value; Node* next; Node* prev; }; void insert(Node*n, int val) { Node*a = new Node; n->next = a; a->next = n->next; a->value = val; n->value = a->value; } 
  • forward_list is a forward_list linked list. It should not have a link to the previous item. And if there is such a link, then this is already a doubly linked list, i.e. list - zed

1 answer 1

Then so:

 void insert(Node*n, int val) { Node*a = new Node; a->value = val; a->next = n->next; n->next = a; a->prev = n; // Не нужно для односвязного списка if (a->next) a->next->prev = a; // Не нужно для односвязного списка } 

Those. you simply insert a new node after n , updating the fields n and a accordingly. n now points to a , and a - where n used to point.

  • at first, it indicates where earlier n indicated, and then n on a, yes? - Estet
  • and it does not matter if you first specify a place, then assign a value and vice versa? - Estet Sep.
  • and what I wrote in the question is that correct? - Estet Sep.
  • and if we allow not to insert after n, but before? - Estet
  • if (a-> next) mean while a-> next! = null? - Estet