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.
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;
}
- Creating the structure of node which contains data and a pointer.
- Then we are creating three different pointers which have struct node data type and allocating heap memory by using malloc function.
- After this assigning the data values and conecting each node with the next pointer.
- 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.