Traverse a DList and insert / remove in place?
Armando
armando.sano at gmail.com
Sun Mar 19 13:59:03 UTC 2023
ok there is the issue of not knowing how to traverse the list
after removing the current element (=> the one that came after of
course). But how about even just keeping a pointer (range) to
'element' that can be used after the list has been traversed in
full to use in remove / insertAfter?
I think I can achieve this with associative arrays (below) but it
seems overkill to use an associative effectively as a DList?
```d
struct myType{
int id;
int prev, next; // id of prev and next
// [...] other stuff
this(int id_, int prev_, int next_)
{
//[...]
}
}
myType[int] list; // key = id
int[] to_remove;
myType[] to_add;
foreach(elem; list)
{
// [...] do something long and complicated with elem, throw a
random number rand
if(rand < 0.5)
to_remove ~= elem.id; // flag for removal
else
to_add ~= myType(some_new_id, elem.id, elem.next); // add
new elem after current
}
foreach(elem; to_add)
list[elem.id] = elem;
foreach(id; to_remove)
{
// reconnect: prev's next to next, and next's prev to prev
list[list[id].prev].next = list[id].next;
list[list[id].next].prev = list[id].prev;
list.remove(id);
}
```
More information about the Digitalmars-d-learn
mailing list