Insert a Component into a Linked List - C Data Structure

C examples for Data Structure:Linked List

Description

Insert a Component into a Linked List

Demo Code

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

struct members {//from   www  .  ja  va 2s. c  o  m
      char name[20];
      struct members *next;
};

typedef struct members node;

void display(node *start);

int main()
{
      node *start, *temp;
    
      start = (node *) malloc(sizeof(node));
      strcpy(start->name, "lina");
      start->next = (node *) malloc(sizeof(node));
      strcpy(start->next->name, "mina");
      start->next->next = (node *) malloc(sizeof(node));
      strcpy(start->next->next->name, "bina");
      start->next->next->next = NULL;
    
      printf("Names of all the members:\n");
      display(start);
    
      printf("\nInserting sita at first position\n");
      temp = (node *) malloc(sizeof(node));
      strcpy(temp->name, "sita");
      temp->next = start;
      start = temp;
      display(start);
    
      printf("\nInserting tina between lina and mina\n");
      temp = (node *) malloc(sizeof(node));
      strcpy(temp->name, "tina");
      temp->next = start->next->next;
      start->next->next = temp;
      display(start);
    
      return(0);
}

void display(node *start)
{
     int flag = 1;
    
     do {
           printf("%s\n", start->name);
           if(start->next == NULL)
                 flag = 0;
           start = start->next;
      } while (flag);
    
     return;
}

Result


Related Tutorials