Denolth Denolth - 1 month ago 6
C Question

Removing from Linked Queue Recursively in C

I've been given this linked queue code for removing an element from a linked queue structure in C. Normally I'd implement this differently, but this code is using recursion. Will it do what it's supposed to do, and why? And if it doesn't, is there a way to fix it so that it does? I'm really new to this recursion thing. Thanks!

typedef struct telement T;
struct telement{
int value;
T* next;
};

void Out (T **A){
if ((*A)->next == NULL){
printf("\n --I'm removing element with value %d.---", (*A)->value);
(*A) = NULL;
free(*A);
}
else{
Out(&(*A)->next);
}
}

Answer

This function does remove the last element. Note that at the last step of recursion, A will point to either the list head pointer, or the second-to-last element's next pointer.

It will then set this pointer to NULL, unlinking the last element from the list.

However, it will not free the last element because free(NULL) does nothing.

Comments