Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Linked List Function

Tags:

c

Here's my function to delete a linked list:

void deleteList( NODE* head )
{
    NODE* temp1; 
    NODE* tempNext;
    temp1 = head;
    tempNext = NULL;

    while( temp1 != NULL )
    {
        tempNext = temp1->next;
        free(temp1);
        temp1 = tempNext;
    }
}

So temp1 first points where the head pointer is pointing. If it isn't NULL, tempNext will be set to point to the next element of the list. Then the first element (temp1) is free'd, and temp1 is reassigned to point to where tempNext is pointing and process repeats.

Is this the right approach to deleting an entire list?

I ask this because when I print the list after using this function, it still prints the list. And IIRC freeing something doesn't delete it but only marks it as available so I'm not sure how to tell if this is correct or not.

like image 600
noobie_programmer Avatar asked Dec 17 '12 15:12

noobie_programmer


People also ask

Which function is used to deleting linked list node?

Deleting the first node : Create a new struct Node* pointer ptr, and make it point to the current head. Assign head to the next member of the list, by head = head->next, because this is going to be the new head of the linked list. Free the pointer ptr. And return the head.

Which function is used to remove all elements from a linked list?

Funktion (deleteall) takes a linked list and a value and delete all the nodes that hold that value, and then return the list after changing.

What is delete function C++?

Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.


1 Answers

Your code looks correct.

You're also correct that freeing a list's elements doesn't immediately change the memory they pointed to. It just returns the memory to the heap manager which may reallocate it in future.

If you want to make sure that client code doesn't continue to use a freed list, you could change deleteList to also NULL their NODE pointer:

void deleteList( NODE** head )
{
    NODE* temp1 = *head;
    /* your code as before */
    *head = NULL;
}
like image 92
simonc Avatar answered Sep 22 '22 15:09

simonc