--- In cprogramming2@yahoogroups.com, Shivakumar <cshiva.in@...> wrote:
>
> Hi Everyone,
>
> I running into a few problems when I try to delete a node
> from a linked list.
>
> I am pasting the small portion of the code.
>
> void remove_product(int pid)
> {
> node *ptr, *temp, *temp2;
> ptr = start;
> while(ptr->next!=NULL)
> {
> if(ptr->product_id==pid)
> {
>
> //For deleting at the beginning of list
> if(ptr==start)
> {
> start = start->next;
> delete ptr;
> return;
> }
>
> //For deleting at the end of list
> if(ptr==end)
> {
> temp = end;
You've forgotten to set
end = end -> prev;
at this point before continuing.
> temp = temp->prev;
> temp->next = NULL;
> delete ptr;
> }
>
> //For deleting in the middle
> temp2 = ptr;
> ptr = ptr->next;
>
> temp2->next = ptr->next;
> delete ptr;
Completely wrong. You need:
temp2 = ptr -> prev;
temp2 -> next = ptr -> next;
ptr -> next -> prev = temp2;
delete ptr;
Don't get my "harsh" wording wrong, such mistakes are completely
normal when dealing with doubly linked lists for the first time or
after you haven't done that for a while.
> }
> }
>
> }
>
> int main(int argc, char *argv[])
> {
>
> if((chr == 'c' || chr == 'C'))
> {
> cout<<"Enter the product id"<<endl;
> cin>>ppid;
> i1->remove_product(ppid);
> }
>
> }
>
>
> deleting from the start of the list works fine, but deleting
> the middle and the end of the list is not happening. Could
> anyone please suggest what is the mistake here?
Regards,
Nico