Skip to main content

Find average of all nodes in a linked list in c

C program for Find average of all nodes in a linked list. Here more information.

// Include header file
#include <stdio.h>
#include <stdlib.h>
/*
  C program for
  Find average of all nodes in a linked list
*/
// Linked list node
typedef struct LinkNode
{
	// Define useful field of LinkNode
	int data;
	struct LinkNode * next;
}LinkNode;

LinkNode * getLinkNode(int data)
{
	// Create dynamic memory of LinkNode
	LinkNode * ref = (LinkNode * ) malloc(sizeof(LinkNode));
	if (ref == NULL)
	{
		// Failed to create memory 
		return NULL;
	}
	ref->data = data;
	ref->next = NULL;
	return ref;
}
typedef struct SingleLL
{
	// Define useful field of SingleLL
	struct LinkNode * head;
	struct LinkNode * tail;
}SingleLL;

SingleLL * getSingleLL()
{
	// Create dynamic memory of SingleLL
	SingleLL * ref = (SingleLL * ) malloc(sizeof(SingleLL));
	if (ref == NULL)
	{
		// Failed to create memory 
		return NULL;
	}
	// Set initial value
	ref->head = NULL;
	ref->tail = NULL;
	return ref;
}
void insert(SingleLL * ref, int data)
{
	LinkNode * node = getLinkNode(data);
	if (ref->head == NULL)
	{
		// Add first node
		ref->head = node;
	}
	else
	{
		// Add node at the end position
		ref->tail->next = node;
	}
	// New last node
	ref->tail = node;
}
// Display linked list element
void display(SingleLL * ref)
{
	if (ref->head == NULL)
	{
		return;
	}
	LinkNode * temp = ref->head;
	// iterating linked list elements
	while (temp != NULL)
	{
		printf(" %d →", temp->data);
		// Visit to next node
		temp = temp->next;
	}
	printf(" NULL\n");
}
// Calculate average of linked list nodes
void findAverage(SingleLL * ref)
{
	if (ref->head == NULL)
	{
		printf("\nEmpty linked List");
	}
	else
	{
		printf(" Linked Linked ");
		display(ref);
		// Define useful resultant variable
		double sum = 0;
		int size = 0;
		// Get first node of linked list
		LinkNode * auxiliary = ref->head;
		// iterating linked list elements
		while (auxiliary != NULL)
		{
			// Node counter
			size++;
			// Calculate the sum of node value
			sum += auxiliary->data;
			// Visit to next node
			auxiliary = auxiliary->next;
		}
		// Display result
		if (sum != 0)
		{
			printf(" Node Average : %0.2f", (sum / size));
		}
		else
		{
			printf(" Node Average : 0");
		}
	}
}
int main()
{
	SingleLL * sll = getSingleLL();
	// Add linked list node
	// 2 → 9 → 1 → 5 → 5 → 4 → 3 → 7 → NULL
	insert(sll, 2);
	insert(sll, 9);
	insert(sll, 1);
	insert(sll, 5);
	insert(sll, 5);
	insert(sll, 4);
	insert(sll, 3);
	insert(sll, 7);
	// Test
	findAverage(sll);
}

Output

 Linked Linked  2 → 9 → 1 → 5 → 5 → 4 → 3 → 7 → NULL
 Node Average : 4.50




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment