Create A Doubly Linked List In C

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.

In Doubly Linked list, traversal can be possible in both direction while in linked list traversal is possible in one direction only.

Create A Doubly 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 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;
}

In the above code, we are doing following things:

  1. Creating the structure for node which contains data and two pointer one for previous node and another for next node.
  2. Then we are creating three different node by allocating heap memory. 
  3. Once they created, we will link them.
  4. After this assigning the data values and conecting each node with the next node and previous node.
  5. 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.

Link of videos which you can refer for understanding.

Hindi

https://youtu.be/63HJ2-jV6Mk

https://youtu.be/c_dqAyQu84A  (C++)

English

https://youtu.be/e9NG_a6Z0mg

Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment