How to delete node in double linked list correctly?

蓝咒 提交于 2019-12-13 08:20:08

问题


void SinglyLinkedList::removeBike(int c)
{
   Node* current = head;

   for(int i = 0; i < c; i++){         // traverse to desired node
       current = current -> next;
   } 

   if(current -> next != NULL && current -> prev != NULL){
        current -> prev -> next = current -> next;
        current -> next -> prev = current -> prev;
        delete current;                     //delete node
   }
   else if(current -> next == NULL){
      current -> prev -> next = current;
      delete current;
   }
   else if(current -> prev == NULL){
       current -> next -> prev = current;
       delete current;
   }    
   else 
       cout << "How did you make it this far?";

}

I'm fairly certain I'm not understanding something here, but research hasn't helped so far.

Logically it makes sense to me but I feel like this is too simple to work, which it isn't.

edited: updated the code minus input check and it breaks on me when I input any int. also I should probably rename the class to doubly linked list... just noticed that


回答1:


Nope, it's definitely not that simple.

First of all if the c parameter exceeds the size of the list, you'll blow up with a null pointer dereference, as your current pointer hits the null pointer on the last node, and blows past it.

Then, if c is 0 or the index of the last element of the list, either it's prev or it's next pointer, accordingly, will be null, and you'll also blow up with a null pointer dereference.

current -> prev -> next = current -> next;
current -> next -> prev = current -> prev;

If current is the first element in the list, current->prev will obviously null. If current is the last element in the list, current->next will obviously be null. Guess what happens when you attempt to dereference the null pointer?

Conclusions:

A) Check that the input parameter to the function is valid.

B) Provide for special handling when the node to be deleted is the first or the last node in the doubly-linked list.

EDIT: by popular request, someone wanted to know how I would fix this:

void SinglyLinkedList::removeBike(int c)
{
   Node* current = head;

   for(int i = 0; i < c; i++){
       if (!current)
           break;
       current = current -> next;
   } 

   if (!current)
           return; // Or throw an exception. Or return a bool false, maybe.

   if (current->prev)
       current -> prev -> next = current -> next;
   else
       head=current->next;

   if (current->next)
       current -> next -> prev = current -> prev;
   else
       tail=current->prev;  // Assuming that there's a tail, somewhere around here...
   delete current;                      //delete node

   // Maybe "return true;" here...
}


来源:https://stackoverflow.com/questions/35566363/how-to-delete-node-in-double-linked-list-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!