Saturday, 23 December 2017

Write a program to count the number of nodes in the singly linked list using C language.

Implementation of the above program in C language:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int data,c,ch;
struct node
{
int element;
struct node *next;
}*L;
void create();
void display(void);
void count(void);
void main()
{
int ch,n,i;
//clrscr();
while(1)
{
printf("\nSINGLY LINKED LIST\n");
printf("\n\n1.Create\n");
printf("2.Display\n");
printf("3.Count\n");
printf("4.Exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1: create(); getch(); break;
case 2: display(); getch(); break;
case 3: count(); getch(); break;
case 4: exit(0); break;
default: printf("\nWrong Choice..."); break;
}
}
}
void create()
{
struct node *temp,*p;
printf("\nEnter the data");
scanf("%d",&data);
temp=malloc(sizeof(struct node));
temp->element=data;
temp->next=NULL;
if(L==NULL)
{
L=temp;
}
else{
p=L;
while(p->next!=NULL)
{
p=p->next;
p->next=temp;
}
}
}
void display()
{
struct node*p;
p=L;
if(L==NULL)
{
printf("\nEmpty");
return;
}
while(p!=NULL)
{
printf("%d \t",p->element);
p=p->next;
}
}
void count()
{
int c=1;
struct node *temp,*next,*p;
if(L==NULL)
{
printf("\nThe lis is empty");
}
p=L;
while(p->next!=NULL)
{
p=p->next;
c++;
}
printf("\nThe no.of elements is %d",c);
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput