pointers - How can I delete a node in my linked list in C++? -
i've pasted work far here: http://codepad.org/whjuujrm
the concepts of linked lists boggle mind, thought i'd practice. know how add nodes, , edit nodes, don't know how remove nodes in particular scenario.
my pseudo code:
previous == - 1; if(stdid == now->getid()); previous->setnext(now->getnext); delete now; return;
how implement this?
the mind-tease in deleting element linked list updating pointer brought element in first place. in list case, top
(and/or possibly bottom
), node's next
. walk through list hunting cur
pointer, keep prev
pointer advance 1 step behind enumerate. assuming find victim node (if don't, there's nothing do, woot!), prev
in 1 of 2 states:
- it null, in case
top
pointer refers victim node ,top
must updated, or... - it pointer node, in case node's
next
member needs updated reflect victim node'snext
member value.
in both cases bottom
may need updating well. in first case bottom
need change if list had 1 node , you're deleting it. i.e. have empty list when finished. easy enough tell, since top
null after detach cur
, set top
equal cur->next
. easier you, since you're keeping size member in list container; if 1
, know both head
, bottom
in second case, last node may victim node. in case bottom
has updated reflect new end of list (which coincidentally in prev
, , may null
if, once again, list had single element. how tell if victim last node in list? if it's next
member null, has last node, , bottom
must updated.
so this, delete function based on id search
void deletestudent(int id) { student *cur = top, *prev = nullptr; while (cur && cur->getid() != id) { prev = cur; cur = cur->getnext(); } // found node? if (cur) { student *pnext = cur->getnext(); // set new next pointer prev, or new top if (prev) prev->setnext(pnext); else top = pnext; // update bottom if needed if (!pnext) bottom = prev; delete cur; --scnt; } }
other delete options , criteria leave you.
best of luck.
Comments
Post a Comment