Singly Linked List: Count number of nodes
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
typedef struct node * NODE;
NODE getnode()
{
NODE x;
x = (NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("\nInsufficient memory");
exit(0);
}
x->link = NULL;
return x;
}
NODE insert(NODE first)
{
int val;
NODE temp, cur;
temp = getnode();
printf("\nEnter the value: ");
scanf("%d", &val);
temp->data = val;
if(first==NULL)
return temp;
cur = first;
while(cur->link!=NULL)
{
cur = cur->link;
}
cur->link = temp;
return first;
}
void countnode(NODE first)
{
NODE cur;
int count=0;
cur = first;
while(cur!=NULL)
{
count++;
cur = cur->link;
}
printf("\nTotal number of nodes are: %d",
count);
}
void display(NODE first)
{
NODE cur;
cur = first;
printf("\nContents are:\n");
if(cur == NULL)
printf("\nList is empty. Nothing to
display.");
else
{
while(cur!=NULL)
{
printf("|
%d | %d | --> ", cur->data, cur->link);
cur =
cur->link;
}
}
}
void main()
{
int ch,i, n;
NODE first = NULL;
printf("\nEnter number of nodes for list:
");
scanf("%d",&n);
for(i=0;i<n;i++)
first = insert(first);
display(first);
countnode(first);
}
Output:
Enter number of nodes for list: 5
Enter the value: 11
Enter the value: 12
Enter the value: 13
Enter the value: 14
Enter the value: 15
Contents are:
| 11 | 4986632 | --> | 12 | 4994056 | --> | 13 | 4994072 | -->
| 14 | 4994088 | --> | 15 | 0 |
Total number of nodes are: 5
Also Check,
Also Check,
No comments:
Post a Comment