Creating a Doubly Linked List
What is a Doubly Linked List?
Doubly linked list is a linear data structure which contain node, each node have two pointer and data, the pointer points to the next node and previous node. The head node previous contains NULL and the last node next part contains 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 doubly 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{
struct node *prev;
int data;
struct node *next;
};
//allocating memory in heap
struct node *head, *middle, *last;
head = malloc(sizeof(struct node));
middle = malloc(sizeof(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->prev= NULL;
head->next= middle;
middle->prev= head;
middle->next= last;
last->prev = middle;
last->next = NULL;
//printing the linked list
struct node *temp = head;
while(temp!=NULL){
printf("%d \t",temp->data);
temp = temp->next;
}
return 0;
}
- Creating the structure for node which contains data and two pointer one for previous node and another for next node.
- Then we are creating three different node by allocating heap memory.
- Once they created, we will link them.
- After this assigning the data values and conecting each node with the next node and previous node.
- 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.