0

I'm trying to delete from a linked list. But it doesn't seems to be working if i try to delete the first element.

if (found)
{
    if (prev == NULL)
    {
        prev = head;
        prev -> next = curr -> next;
        delete curr;
    }
    else
    {
        prev -> next = curr -> next;
        delete curr;
    }
}

return found;

The findNode functions works if i were to delete from somewhere in the middle or from the tail. But i figured out that if i delete from the tail, i've have to set the next to NULL, am i right?

3
  • Can you show the findNode function? Most important is how you pass (and set) the prev and curr arguments. Commented Feb 14, 2013 at 17:39
  • i you have a header node, why doesn't then prev point to to that header node already after a successful search for first node Commented Feb 14, 2013 at 17:43
  • When showing a function, please show the complete function, including the function header. Commented Feb 14, 2013 at 17:45

2 Answers 2

1

The problem is probably that you don't actually change the head to point to the new head of the list. You have to change the head:

if (prev == NULL)
{
    head = head->next;  // Set `head` to point to the next node, i.e. the new `head`
    delete curr;
}
Sign up to request clarification or add additional context in comments.

1 Comment

gosh what a dumb mistake i did there. thanks for the help guys! solved. i changed prev = head; prev -> next = curr -> next; to head = curr -> next;
0

Assuming that findNode is correct and sets prev to the node before curr (might want to consider a doubly linked list) then

   if (prev == NULL)
   {
      prev = head;
      prev -> next = curr -> next;
      delete curr;
   }

is incorrect. Since when prev is NULL it is the head node that is the one found.

So the code should be

   if (prev == NULL)
   {
      head = head->next;
      delete curr;
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.