Doubly Linked List In C

What is a Doubly Linked List?

A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes.

Difference Between Singly And Doubly Linked List

Doubly linked list consists of pointer to next node as well as pointer to previous node while singly linked list consists of pointer to next node only. So accordingly the different operations that we do perform on linked list vary in coding.

Problem: Write a C program to create a doubly linked list and to perform different operations on it such as

1] Display
2] Add New Node
3] Calculate Length of Linked List
4] Delete A Node By Position
5] Delete A Node By Data It Contains
6] Search For Given Data In Linked List

Solution:
  1. First, create the structure,
    typedef struct DLL
    {
     int data;
     struct DLL *next,*prev;
    }NODE;
    
    We just included the previous pointer in the structure that we used for singly linked list.

  2. Now look at the modified create function singly linked list
    NODE  *create(NODE * head)
    {
    
     NODE *temp,*nn;
     int size,i;
    
     printf("\n How many nodes do you want to create:- ");
     scanf(" %d",&size);
    
     for(i=0;i<size;i++)
     {
      nn=(NODE *)malloc(sizeof(NODE *));
    
      printf("\n Enter node data:- ");
      scanf(" %d",&nn->data);
    
      nn->next=nn->prev=NULL; //Look at here nn->prev is also set to NULL
    
      if(head==NULL)
       head=temp=nn;
      else
      {
      temp->next=nn;
      nn->prev=temp; // Setting the new node of previous to temp i.e previous node
      temp=nn;
      }
     }
    
     return head;
    }
    
    Look at illustration below:

    Doubly Linked List In C

    What is happening here

    1. First we created a new node then assigned NULL to nn->prev and nn->next
    2. When at first head was empty we called new node as temp and head.
    3. For upcoming nodes we stored addresses of next and previous nodes in each node in nn->>next and nn->prev respectively.
    4. When required number of nodes we returned the address of head of linked list.

  3. Display function will remain same as for singly linked list

C Program:

Get This Program:  

Problem: Write a c program to create a doubly circular linked list and perform different operations on it. (Same operations as in doubly linked list)

C Program:

Get This Program: