Learn C - C Structure Examples

Doubly Linked Lists

A doubly linked list can go through a list in either direction.

We need an extra pointer in each structure to store the address of the previous structure in addition to the pointer to the next.

#include <stdio.h> 
#include <ctype.h> 
#include <stdlib.h> 
  //w w  w . j  av a  2 s  . c  o  m
typedef struct Dog Dog;       // Define Dog as a type name 
struct Dog                      // Structure type definition 
  int age; 
  int height; 
  char name[20]; 
  char father[20]; 
  char mother[20]; 
  Dog *next;                    // Pointer to next structure 
  Dog *previous;                // Pointer to previous structure 
int main(void) { 
  Dog *first = NULL;            // Pointer to first Dog 
  Dog *current = NULL;          // Pointer to current Dog 
  Dog *last = NULL;             // Pointer to previous Dog 
  char test = '\0';               // Test value for ending input 
  for( ; ; ) { 
    printf_s("Do you want to enter details of a%s Dog (Y or N)? ", first != NULL?"nother" : ""); 
    scanf_s(" %c", &test, sizeof(test)); 
    if(tolower(test) == 'n') 
    // Allocate memory for each new Dog structure 
    current = (Dog*) malloc(sizeof(Dog)); 
    if(first == NULL){ 
      first = current;            // Set pointer to first Dog 
     current->previous = NULL; 
    } else { 
      last->next = current;       // Set next address for previous Dog 
      current->previous = last;   // Previous address for current Dog 
    printf_s("Enter the name of the Dog: "); 
    scanf_s("%s", current->name, sizeof(current->name)); 

    printf_s("How old is %s? ", current->name); 
    scanf_s("%d", &current->age); 

    printf_s("How high is %s ( in hands )? ", current -> name ); 
    scanf_s("%d", &current->height); 

    printf_s("Who is %s's father? ", current->name); 
    scanf_s("%s", current->father,sizeof(current->father)); 

    printf_s("Who is %s's mother? ", current->name); 
    scanf_s("%s", current->mother, sizeof(current->mother)); 

    current->next = NULL;         // In case it's the last... 
    last = current;               // ...save its address 

  // Now tell them what we know. 
  while(current != NULL)          // Output Dog data in reverse order 
    printf_s("%s is %d years old, %d hands high,", 
               current->name, current->age, current->height); 
    printf_s(" and has %s and %s as parents.\n", current->father, 
    last = current;               // Save pointer to enable memory to be freed 
    current = current->previous;  // current points to previous in list 
    free(last);                   // Free memory for the Dog we output 
    last = NULL; 
  first = NULL; 
  return 0; 

The code above generates the following result.