Friday, August 9, 2013

Simple Linked List -for my reference !!


#include "stdio.h"
#include "stdlib.h"


struct node {
   
   int   data;
   struct node* next;
};

int length(struct node *head){
    
    struct node* current = head;
    int count = 0;
    while ( current != NULL ){
          
          count++;
          current = current -> next;
    }
return count;
}

void display(struct node *head) {
     
      
    struct node* current = head;
    int count = 0;
    while ( current != NULL ){
          
          printf("%d \t", current -> data);
          current = current -> next;
    } 
    printf("\n \n");
}
     
int main(){

    int k = 0;
    struct node* head = NULL;
    struct node* second = NULL;
    struct node* third = NULL;
    struct node* twothree = NULL;
    
    head = malloc (sizeof (struct node));
    second = malloc (sizeof (struct node));
    third = malloc (sizeof (struct node));
    twothree = malloc (sizeof(struct node));
  
    head -> data = 1;
    head -> next = second ;
    
    second -> data = 2;
    second -> next = third;
    
    third -> data = 3;
    third -> next = NULL;
    
    printf("List with three elements \n");
   
    display(head);
    k = length(head);
    printf("\n adding a node in between second and third \n");
    
    twothree -> data = 10;
    second -> next = twothree;
    twothree -> next = third;
    
    display(head);
    k = length(head);
    display(head);
    
    printf ("\nThe length of the list %d\n \n", k);
    
    printf ("\nDeleting a node twothree \n \n");
    
    second -> next = third;
    
    k = length(head);
    display(head);
    printf ("The length of the list %d \n \n", k);
    
    
getch();
return 0;
}
    

No comments: