Demonstrates the fundamentals of using a linked list. - C Data Structure

C examples for Data Structure:Linked List

Description

Demonstrates the fundamentals of using a linked list.

Demo Code

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/* The list data structure. */
struct data {/*  w  w  w.j  a  v a 2s  .  c  o  m*/
   char name[20];
   struct data *next;
};

/* Define typedefs for the structure and a pointer to it. */
typedef struct data PERSON;
typedef PERSON *LINK;

int main(void)
{
   LINK head = NULL;
   LINK new1 = NULL;
   LINK current = NULL;

   new1 = (LINK)malloc(sizeof(PERSON));
   new1->next = head;
   head = new1;
   strcpy(new1->name, "A");

   current = head;
   while (current->next != NULL) {
      current = current->next;
   }

   new1 = (LINK)malloc(sizeof(PERSON));
   current->next = new1;
   new1->next = NULL;
   strcpy(new1->name, "C");

   new1 = (LINK)malloc(sizeof(PERSON));
   new1->next = head->next;
   head->next = new1;
   strcpy(new1->name, "B");

   current = head;

   while (current != NULL) {
      printf("\n%s", current->name);
      current = current->next;
   }

   printf("\n");

   return 0;
}

Result


Related Tutorials