Search code examples
cpointersrecursionlinked-listbag

delete Certain number from linked list (recursive)


hello everyone i'm trying to create a function that delete a Certain number from all the cells in the linked list that have this number but my deleting function only deleting the first cell that he arrive to the end and then returning to the main this is my code:

struct num* deleteCell(struct num* point, int numdelete)
{
    struct num* tempdelete = point;
    if (point == NULL)  // found the tail and dont found any match to delete
    {
        printf("not found\n");
        return NULL;
    }
    else if (point->number == numdelete)// found one to delete
    { 
        tempdelete = point->pNext;
        free(point);
    }
    else// Just keep going 
    { 
        point->pNext = deleteCell(point->pNext, numdelete);
    }
    return tempdelete;
}

(point is the pointer to the first cell ,numdelete is the number that i want to delete ) thanks for helpers!!!!

alon


Solution

  • struct num* deleteCell(struct num* point, int numdelete) {
      if (point == NULL) {
         return NULL;
      }
    
      if (point->number == numdelete) { 
        num* tempdelete = point->pNext;
        free(point);
        return deleteCell(tempdelete, numdelete);
      }
    
      point->pNext = deleteCell(point->pNext, numdelete);
      return point;
    }