Home Linked List Length of a Linked List

Length of a Linked List

1954
0
Length of Linked List

Problem Statement: Print the number or count of
elements in the Linked List

/*C code to create and print the Linked List*/
#include <stdio.h>
#include <stdlib.h>

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

NODE *head = NULL;

NODE *newNodeF(int key)
{
	NODE *temp = (NODE *)malloc(sizeof(NODE));
	temp->data = key;
	temp->next = NULL;
	return temp;
}

void createList()
{
	NODE *temp, *newNode = NULL;
	int n, data;
	printf("Enter number of elements	");
	scanf("%d", &n);
	printf("Enter elements\n");
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &data);
		newNode = newNodeF(data);
		if (head == NULL)
		{
			head = newNode;
		}
		else
		{
			temp = head;
			while (temp->next != NULL)
			{
				temp = temp->next;
			}
			temp->next = newNode;
		}
	}
}

int count()
{
	NODE *temp = head;
	if (temp == NULL)
	{
		return 0;
	}
	int count = 0;
	while (temp != NULL)
	{
		count++;
		temp = temp->next;
	}
        return count;
}
void printList()
{
	NODE *temp = head;
	if (temp == NULL)
	{
		printf("List is empty!\n");
		return;
	}
	printf("Linked List is\t");
	while (temp != NULL)
	{
		printf("%d--> ", temp->data);
		temp = temp->next;
	}
}

int main()
{
	printList();
	createList();
	printList();
	printf("NULL\n");
        printf("Count of Linked List is %d",count());
	return 0;
}


$ gcc countll.c
$ ./a.out
List is empty!
Enter number of elements 5
Enter elements
1
2
3
4
5
Linked List is 1–> 2–> 3–> 4–> 5–> NULL
Count of Linked List is 5$

also see

C Programming language
Go Programming language
Linked List Array
Stack Queue
Puzzle Reasoning
Aptitude HTML
Previous articleAptitude Simplification
Next articleC Program to Print Reverse Array

LEAVE A REPLY

Please enter your comment!
Please enter your name here