Solved programming problem

Find Single Linked List Size in C.

Source code

#include <stdio.h>

struct list

{

    int data;

    struct list *next;

};

typedef struct list node;

int total(node * head)

{

    node *temp = head;

    int count=0;

    while(temp!=NULL) ///count the length

    {

        count++;

        temp=temp->next;

    }

    return count;

}

int main()

{

    node *head,*start,*last,*temp;

    int flag;

    start=NULL;

    do

    {

        printf("Press 1 to Inset a Value: ");

        scanf("%d",&flag);

        if(flag!=1){ break;}

        temp = (node *)malloc(sizeof(node));

        printf("Enter the Value: ");

        scanf("%d",&temp->data);

        temp->next=NULL;

        if(start==NULL) ///check the first value

        {

            start = temp;

            head = temp;

        }

        else

        {

            last = start;

            while(last->next != NULL)  //find last index

            {

                last = last->next;

            }

            last->next = temp; ///replace new value at last

        }

    }while(flag==1);

    int size=total(head);

    printf("
Size of The Linked List is: %d 
",size);

    return 0;

}

Output

Press 1 to Inset a Value: 1
Enter the Value: 6
Press 1 to Inset a Value: 1
Enter the Value: 7
Press 1 to Inset a Value: 1
Enter the Value: 9
Press 1 to Inset a Value: 1
Enter the Value: 9
Press 1 to Inset a Value: 0

Size of The Linked List is: 4

Join the discussion

Add your comment