2
votes

I am writing a function which removes a specific node from the linked list. The function works for most cases but does not work when the node to delete is either the head node, or the only node in the linked list. I tried setting the current to equal NULL when this case happens but that creates a segmentation fault, where is my logic wrong?

void deleteNodeAfter(Node *head, Node *delete) {
    bool remove = false;
    Node *current = head;
    Node *delNode = delete;
    if (current->songName == delNode->songName){
        current= NULL;
        remove = true;
    }
    while (!remove) {
        if (current->link->songName == delNode->songName) {
            current->link = delNode->link;
            remove = true;
            // free(delNode);
        } else {
            current = current->link;
        }
    }
}
2
I don't think if (current->link->songName == delNode->songName) does what to expect it to do. - Jasen
It depends on how you define your list and whether you are using a dummy node for head or not. See: How to create a Minimal, Complete, and Verifiable example. - David C. Rankin

2 Answers

0
votes

If you delete the first you need to update originla list pointer:

void deleteNodeAfter(Node **head, Node *delete) {
   Node *current = *head;
   if( first ) {
     *head = (*head)->next;
     free(current);
   }
}

You need to pass pointer to pointer to first instead of pointer to first. Using:

Node *head;
Node *after;
...
deleteNodeAfter( &head, after );
0
votes
void deleteNodeAfter(Node **head, Node *delete) {
  bool remove = false;
  Node *current;
  while(current=*head;head=&(current->next),current=*head;current)
  {
    if (current->songName == delNode->songName){
      // perhaps the above check should be   current==delNode
      *head=current->next
      free(current)
      return;
    }
  }
}

You need to pass in a pointer to the pointer to the list so that the pointer-to-llist can be updated by the delete operation.