I could not grasp the reason we create pointers of nodes instead of node structures when we try to implement linked lists as here:
typedef struct node {
int val;
struct node * next;
} node_t;
and
node_t * head = NULL;
head = malloc(sizeof(node_t));
if (head == NULL) {
return 1;
}
head->val = 1;
head->next = NULL;
here, why do we declare nodes such as head
as pointers of structures instead of direct structures>
In the linked list if the head pointer has to point to some other node we need to use the double pointer when it is passing to a function.
The pointer always points to the next member of the list. If the pointer is NULL, then it is the last node in the list. A linked list is held using a local pointer variable which points to the first item of the list. If that pointer is also NULL, then the list is considered to be empty.
node *next ensures that you've a variable next which is a pointer to the node . int *next would mean that next would point to an integer and not the node , won't give you the linked list, which is what you seem to be looking for.
Having head
as a pointer allows for things like empty lists (head == NULL
) or a simple way to delete elements at the front of the list, by moving the head
pointer to another (e.g. second) element in the list. Having head
as a structure, these operations would be impossible or at least much less efficient to implement.
The primary reason is that the C language simply won't allow it - a struct
type cannot contain an instance of itself. There are two reasons for this:
The struct
type is not complete until the closing }
, and you cannot create an instance of an incomplete type;
If a struct
type could contain an instance of itself, then the instance would be infinitely large (struct foo
contains an instance of struct foo
, which contains an instance of struct foo
, which contains an instance of struct foo
, ad infinitum).
You can, however, create pointers to incomplete types (since the size of the pointer doesn't depend on the size of the pointed-to type). So if you want a struct
type to contain a member that refers to another instance of the same type, it must be done through a pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With