Home > Enterprise >  Why nested structure is needed in singly linked list?
Why nested structure is needed in singly linked list?

Time:02-07

I'm new to data structuure and algorithm. Right know I'm learning singly linked and I'm confused with a piece of code that creates linked list.

#include<stdio.h>
#include<stdlib.h>

struct node
{
    int data;
    struct node *next;
};

int main()
{
    int n;
    struct node *head = NULL;
    head = malloc(sizeof(struct node));

    head->data = 36; 
    head->next = NULL;

    printf("%d", head->data);
}

My question is why we have to use struct node *next; command in order to initialise memory location of next node. Instead we can use int *next?

CodePudding user response:

This definition

struct node
{
    int data;
    struct node *next;
};

explains
"This is a node, carrying info on an int and pointing to another node (if not NULL), which in turn might point to yet another node... and so on."
A typical linked list.

This is what I understand your alternative to be:

struct node
{
    int data;
    int *next;
};

And it would explain:
"This is a node, carrying info on an int and pointing to another int (if not NULL)."
But an int cannot provide access to yet another int. So this one can provide access to info on one or two ints.
The idea of a linked list, in contrast, is however that it can (assuming memory) provide access to an indeterminate and quite high number of nodes.

CodePudding user response:

In fact, you may write like

struct node
{
    int data;
    int *next;
};

To allocate the head node you can write (as you already did)

head = malloc(sizeof(struct node));

head->data = 36; 
head->next = NULL;

If you want to allocate the next node you have to write

head->next = malloc( sizeof( struct node ) );

But to assign values to the newly created node you have to write

( ( struct node * )head->next )->data = 37;
( ( struct node * )head->next )->next = NULL;

Such a code will only confuse readers of the code.

That is you are allocating memory for an object of the type struct node but then you are interpreting the pointer to the allocated memory as having the type int * instead of using a pointer of the type struct node *. And then again to assign values tp an object of the type struct node you need to cast the pointer of the type int * to the type struct node *. Such a code is error-prone.

  •  Tags:  
  • Related