C examples for Data Structure:Linked List
Create Doubly Linked Lists
#include <stdio.h> #include <ctype.h> #include <stdlib.h> typedef struct Horse Horse; // Define Horse as a type name struct Horse // Structure type definition { int age;/* w ww. j a v a 2 s. co m*/ int height; char name[20]; char father[20]; char mother[20]; Horse *next; // Pointer to next structure Horse *previous; // Pointer to previous structure }; int main(void) { Horse *first = NULL; // Pointer to first horse Horse *current = NULL; // Pointer to current horse Horse *last = NULL; // Pointer to previous horse char test = '\0'; // Test value for ending input for( ; ; ) { printf("another (Y or N)? "); scanf(" %c", &test, sizeof(test)); if(tolower(test) == 'n') break; // Allocate memory for each new horse structure current = (Horse*) malloc(sizeof(Horse)); if(first == NULL) { first = current; // Set pointer to first horse current->previous = NULL; } else { last->next = current; // Set next address for previous horse current->previous = last; // Previous address for current horse } printf("Enter the name of the horse: "); scanf("%s", current->name, sizeof(current->name)); printf("How old is %s? ", current->name); scanf("%d", ¤t->age); printf("How high is %s ( in hands )? ", current -> name ); scanf("%d", ¤t->height); printf("Who is %s's father? ", current->name); scanf("%s", current->father,sizeof(current->father)); printf("Who is %s's mother? ", current->name); scanf("%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. printf("\n"); while(current != NULL) // Output horse data in reverse order { printf("%s is %d years old, %d hands high,", current->name, current->age, current->height); printf(" and has %s and %s as parents.\n", current->father, current->mother); 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 horse we output last = NULL; } first = NULL; return 0; }