Count number of nodes in Linked List

http://install4install.com

Counting refers to calculating number of nodes present in linked list.

Counting

Counting

Program

#include<stdio.h>
struct node
{
    int item;
    struct node *next
};
int main()
{
    struct node *start,*list,*temp;
    int i;

    start = (struct node *)malloc(sizeof(struct node));
    list = start;
    start->next = NULL;
    for(i=1;i<5;i++)
    {   
        list->item = i;
        list->next = (struct node *)malloc(sizeof(struct node));
        list = list->next;
       }
    list->next = NULL;
    temp = start;
    int length =0;
    while(temp!=NULL)//Fig 2
    {

    	if (temp->next == NULL) 
    	  {
           break;
    	  }
         else
        {
        length++;
        temp=temp->next;
        }
    }    

printf("Length of Linked List : %d \n",length);
printf("Elements of linked lists are :\n");
   while(start != NULL)
    {   
    	if (start->next == NULL) 
    	  {
           break;
    	  }
        printf("%d\n",start->item);
        start = start->next;
    } 
return 0;
}

Run

Illustration of Program

Screen Shot 2014-04-07 at 1.48.39 PM

Fig 1 : Linked List

Screen Shot 2014-04-07 at 2.14.02 PM

Fig 2 : Working of Program



Short URL: http://tinyit.cc/e0eb10
Author: Cusp2207 on April 7, 2014
Category: Algorithms, Computer Science, Data Structures
Tags:

Leave a Reply

Last articles