Creating linked list Dynamically ( Dynamic Memory Allocation) part – 1

We have seen representation of linear data structures by using sequential allocation method of storage ,as in arrays. But sometimes linear memory allocation is unacceptable in a program ,this can be due to various reason like  Unpredictable storage requirements for the program and can be due to extensive data manipulation takes .To satisfy these requirements linked list came which allocates memory dynamically  .

There is a huge difference between how data is stored in a Array and Linked list. In arrays the memory allocation is continuous . Consider the below figure which represents memory allocation through arrays.

Where as in Linked list the memory allocation is not continuous .  A linked list consists of nodes and that contains data and address of the next node in the list

Now lets write a simple program to implement linked list through structures ..

main()

{

Struct node {

int data;

struct node *next ;

}

struct node *p;

P=(struct node *)malloc(4); /* malloc() will allocate continuous memory and than return the address of the memory location of the data where memory is allocated

(*p).data = 10;

(*p).next=null;

}

This is how memory will be allocated to this program —– >

Now consider the following c program to display data present in every node of the given linked list :

Programe :

display(struct node *s)

{

if (s==null){

return;

}

else {

while (s!=Null)

{

Printf(“%d”,s->data);

s=s->next;

}

}

}

output of the above program will be : a b c d e f

continued …

Leave a Reply

Your email address will not be published. Required fields are marked *