Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a C Linked List why are the nodes also pointers? [duplicate]

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>

like image 688
Huzo Avatar asked Feb 16 '18 13:02

Huzo


People also ask

Why do we pass double pointers in linked list?

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.

Why do we use pointers in linked list?

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.

Why we use node * next in linked list?

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.


2 Answers

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.

like image 145
Mithrandir Avatar answered Jan 01 '23 12:01

Mithrandir


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:

  1. The struct type is not complete until the closing }, and you cannot create an instance of an incomplete type;

  2. 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.

like image 36
John Bode Avatar answered Jan 01 '23 12:01

John Bode