Creating A Linked List In C

Creating A Linked List In C

What is a Linked List?

Linked list is a linear data structure which contain node, each node have data and a reference pointer, the pointer points to the next node and the last node contains data and NULL value.


Creating A Linked List In C


Advantage of using Linked List Over array;

We can change the size of linked list whenever we want in linked list, but not in array.


How to create a linked list?


#include<stdio.h>


// creating a Linked list 

int main(){

  

//node contain int data and next pointer of struct node data type

struct node{

    int data;

    struct node *next;

};


//allocating memory in heap

struct node *head = malloc(sizeof(struct node));

struct node *middle = malloc(sizeof(struct node));

struct node *last = malloc(sizeof(struct node));


//assigning value to each node

head->data = 10;

middle->data = 20;

last->data = 30;


//linking the nodes

head->next= middle;

middle->next= last;

last->next = NULL;



//printing the linked list

struct node *temp = head;


while(temp!=NULL){

    printf("%d \n",temp->data);

    temp = temp->next;

}

    return 0;

}



In the above code, we are doing following things:

  1. Creating the structure of node which contains data and a pointer.
  2. Then we are creating three different pointers which have struct node data type and allocating heap memory by using malloc function.
  3. After this assigning the data values and conecting each node with the next pointer.
  4. For printing we are using another temp pointer of struct node data type, temp basically traverse from one node to another node and print the value.

But why we are creating pointers for node??

Well, the answer is simple we are using pointer which points to some node. We are using pointer to store the address of the node. For more details you can read about pointer to structure.
Load comments