c++ - How to move elements in doubly linked list? -
i have custom list (doubly linked list , not std::list) implemented in code. requirement move element 1 left or right updating references. possible?
class elem { elem *next; elem *prev; }
.......
void move_element_left(elem *e) { if(e->prev()==null) return; //left ... return elem *left = e->prev(); left->next() = e->next(); e->prev() = left->prev(); if (left->next()) left->next()->prev() = left; if (e->prev()) e->prev()->next() = e; e->next() = left; left->prev() = e; }
.......
int main() { elemlist ls; ... ... move_element_left(e); //e of type elem * ... }
above code works except 2nd object in list want move left (or top most). (i.e. if list(obj5, obj9, obj11, obj12,..), moving obj9 first in list gives error)
works designed ?
following code in schema, shows works designed:
void move_element_left(elem *e) { if(e->prev()==null) return; //ok ! left ... return elem *left = e->prev(); // ok ! (1) left->next() = e->next(); // ok ! (2) e->prev() = left->prev(); // ok ! (3) if (left->next()) // ok ! left->next()->prev() = left; // ok ! (4) if (e->prev()) // ok ! e prev left prev null e->prev()->next() = e; e->next() = left; // ok ! (5) left->prev() = e; // ok ! (6) }
here schema (sorry childish aspect ;-) ):
so list in fact fine. problem elemlist
contains pointer head of list . , pointer still points old first , second element. list no longer consitent.
how fix ?
one way out, make move_element_left()
member function of elemlist
. in case take care of special case e->left
becomes null, in case need update elemlist's pointer first element.
Comments
Post a Comment