#include <stdio.h>
#include
<stdlib.h>
{
int data;
struct Node* next;
};
struct
Node* createNode(int value)
{
struct Node* newNode = (struct
Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
void
insertEnd(struct Node** head, int value)
{
struct Node* newNode = createNode(value);
if (*head == NULL)
{
*head = newNode;
}
else
{
struct Node* current = *head;
while (current->next != NULL)
{
current = current->next;
}
current->next = newNode;
}
}
int
countNodes(struct Node* head)
{
int count = 0;
while (head != NULL)
{
count++;
head = head->next;
}
return count;
}
void
displayList(struct Node* head)
{
while (head != NULL)
{
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
void
main()
{
struct Node* head = NULL;
int num, value;
printf("Enter number of nodes:
");
scanf("%d", &num);
for (int i = 0; i < num; i++)
{
printf("Enter value for node %d:
", i + 1);
scanf("%d", &value);
insertEnd(&head, value);
}
printf("Linked list elements: ");
displayList(head);
printf("Total number of nodes:
%d\n", countNodes(head));
// Free memory
while (head != NULL)
{
struct Node* temp = head;
head = head->next;
free(temp);
}
}
No comments:
Post a Comment