2

Got a question in my exam.

Write a function DeleteList() that takes a list, deallocates all of its memory and sets its head pointer to NULL (the empty list).

Solution was given as

void DeleteList(struct node** headRef) {
    struct node* current = *headRef;
    struct node* next;
    while (current != NULL) {
        next = current->next; 
        free(current); 
        current = next; 
    }
    *headRef = NULL;
}

My solution :

void DeleteList(struct node** headRef) {
    struct node* current = *headRef;

    while (current != NULL) {
        *headRef = *headRef->next;
         free(current);
         current = * headRef;
    }
    free(current);
    *headRef = NULL;
}

Is this correct approach? Thanks,

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Thinker
  • 6,820
  • 9
  • 27
  • 54
  • Have you tried it, did it work? – Kninnug Apr 13 '13 at 19:27
  • 1
    I don't think that `*headRef->next` binds the way you think it does. – CB Bailey Apr 13 '13 at 20:03
  • 1
    Apart from the precedence error - `*headRef = *headRef->next;` should be `*headRef = (*headRef)->next;`, it wouldn't compile otherwise - it's correct. But the `free(current);` after the while loop is superfluous and should be removed. – Daniel Fischer Apr 13 '13 at 20:31

3 Answers3

1

Your solution does not do this "and sets its head pointer to NULL" because the final line of your proposal (*headRef = NULL;) is no longer setting the incoming headRef value to NULL, but rather the final Next point in the list (which already is null).

Pieter Geerkens
  • 11,775
  • 2
  • 32
  • 52
  • The simplest way would be to declare and use a variable called `next` in place of `headRef`, as per the published solution, so that `headRef` is the correct location when the routine completes. – Pieter Geerkens Apr 14 '13 at 04:38
0
free(current); //you should remove this line after the while loop because when while loop breaks the current is already NULL so free(NULL) makes no sense. 
*headRef = NULL;

look here Free(NULL).

The rest must work according to me.

Community
  • 1
  • 1
nommyravian
  • 1,316
  • 2
  • 12
  • 30
0
void DeleteList(struct node **headRef)
{
    struct node *current = *headRef;

    while (current) {
         *headRef = (*headRef)->next;
         free(current);
         current = *headRef;
    }
    *headRef = NULL;
}
Valeri Atamaniouk
  • 5,125
  • 2
  • 16
  • 18