Deleting Node in Linked List C++ -
so i've been searching forums, im still new language , linked lists can barely decipher results.
basically made delete function linked list. can create list, traverse list, sort list, search list, , insert before node in linked list. recycled code insert locate point in list delete. main point of confusion how link previous points node after 1 deleting.
i won't write whole new linked list implementation can point out of problems code you.
the trick stay 1 node ahead of 1 want delete.
i have renamed entry
current
clarity
nodetype *current , *first, *next; int akey; // line search start second element. // current =start->ptr; // should current = start; // not needed. assuming last node has null value '->ptr' // last=start; next = current->ptr; cout<<"input data delete"<<endl; cin>>akey; // check if first node contains data // assuming list have @ least 1 element. i.e. current not null while (current->adata == akey) { // delete it. delete current; // update current while loop current = next; // update next too. next = current->ptr; } // know first element doesn't contain data. // update pointer begging of new list if removed top. first = current; // has unnecessary checks. // ****specifically (akey!=current->adata) // prevent entering loop if false. // while((akey!=current->adata)&&(current->ptr !=null)) while(next != null) // should enough { if(next->adata == akey) { // make current node (before 'deletion point') // lined 1 after 'deletion point (next of next) current->ptr = next->ptr; // delete node. delete next; // make next pointer point new next. next = current->ptr } // otherwise advance both current , next. else { current = next; next = next->ptr; } } // use test it. current = first; while(current){ cout<<current->adata<<", "; current = current->ptr; }
this not cleanest way. similar implementation can see went wrong.
Comments
Post a Comment