I'm writing the oh-so common methods of deleted a node from a singly linked list, but I'm unsure if the way I'm deleting them (by using FREE()) is correct. I want to truly delete the node and free up the memory. I have provided the strut definition for Node as well as how Node structs are created.
I understand in Java anytime nothing is pointing to data, it is cleaned up automatically. I figured for C, I have to use free, but am I using it correctly? For example below, when I 'free' current, am I able to make current reference something else after? What is the best way to do this?
Thanks and I hope my question is clear!
typedef struct Node {
int data;
struct Node *next;
} Node;
struct Node* newNode(int value) {
struct Node* node = (Node *)malloc(sizeof(struct Node));
if (node == NULL) {
// malloc fails. deal with it.
} else {
node->data = value;
node->next = NULL;
}
return node;
}
void delete(int value, struct node *head) {
struct Node* current = head;
struct Node* previous = NULL;
while (current != NULL) {
if (current->data == value) {
if (previous == NULL) {
current = current->next;
free(head);
} else {
previous->next = current->next;
free(current);
current = previous->next;
}
} else {
previous = current;
current = current->next;
}
}
}