Naveed Farahani
Naveed Farahani

Reputation: 21

Deleting head or only node in Linked List in C

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;
        }
    }
}

Upvotes: 2

Views: 576

Answers (2)

Jasen
Jasen

Reputation: 12392

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.

Upvotes: 0

user394010
user394010

Reputation: 374

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 );

Upvotes: 0

Related Questions