Doubly linked list

Nodes in a doubly linked list are linked in both directions using next and previous pointer. Two consecutive elements are linked by previous and next pointer. Thus it is possible to traverse any direction from head to tail or from tail to head. The limitation of single linked list thus has been eliminated and most of the practical and applied list has this type of structure inside it. Find the visual representation of the doubly linked list in the below figure.

Doubly linked list - pictorial view

Doubly Linked list

Doubly linked list source code

#include <stdio.h>
#include <conio.h>

typedef struct _dlist_node
{
  int node_value;
  struct _dlist_node * prev;
  struct _dlist_node * next;

}dlist_node;

int main(int argc, char *argv[])
{
  int key, i;
  dlist_node *head, *temp, *current, *tail;
  head = NULL;
  temp = NULL;
  current = NULL;
  printf ("Doubly linked list demo application\n");
  do
  {
    printf("Add a node [y/n] : ");
    key = getch();
    if(key == 'y')
    {
      temp = (dlist_node *)malloc(sizeof(dlist_node));
      if(temp != NULL)
      {
        printf ("Value of this node : ");
        scanf ("%d", &temp->node_value);
        temp->prev = NULL;
        temp->next = NULL;
        if(head == NULL)
        {
          current = temp;
          head = temp;
        }
        else
        {
          current->next = temp;
          temp->prev = current;
          current = temp;
        }
      }
      else
      {
        printf ("Memory allocation error!");
        return -1;
      }

    }
    else
    {
      break;
    }

  } while (1);
  tail = current;
  current = head;
  i = 0;
  printf ("List Contains(sequence head to tail):\n");
  while (current)
  {
    printf ("Node %d, Value: %d\n", i + 1, current->node_value);
    i++;
    current = current->next;
  }

  current = tail;
  i = 0;
  printf ("List Contains(sequence tail to head):\n");
  while(current)
  {
    printf ("Node %d, Value: %d\n", i + 1, current->node_value);
    i++;
    current = current->prev;
  }

  return 0;
}

Output

Doubly linked list demo application
Add a node [y/n] : y
Value of this node : 1
Add a node [y/n] : y
Value of this node : 10
Add a node [y/n] : y
Value of this node : 100
Add a node [y/n] : n
List Contains(sequence head to tail):
Node 1, Value: 1
Node 2, Value: 10
Node 3, Value: 100
List Contains(sequence tail to head):
Node 1, Value: 100
Node 2, Value: 10
Node 3, Value: 1

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#