Solution:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node* head=NULL;
struct node *cn()
{
struct node* n;
n=(struct node *)malloc(sizeof(struct node));
return(n);
}
void createnode() //Function to create Linked list.
{
int i,n,x;
struct node * temp,*newnode;
printf("Enter size of linked list :\n");
scanf("%d",&n);
printf("Enter elements of linked list :\n");
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(head==NULL) //checking in linked list is empty
{
head=cn();
head->data=x;
head->next=NULL;
temp=head;
}
else
{
newnode=cn();
newnode->data=x;
newnode->next=NULL;
temp->next=newnode;
temp=newnode;
}
}
}
void traverse() //Function to traverse Linked list.
{
struct node * temp;
int cnt=0;
temp=head;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
cnt++;
}
printf("Total number of node :%d",cnt);
}
void main()
{
int choice,a=0;
while(choice!=3)
{
printf("\n\n1. Create Linked list.\n");
printf("2. Display Linked list.\n");
printf("3. Exit\n\n");
scanf("%d",&choice);
printf("\n");
switch(choice)
{
case 1: if(a==1)
{
printf("You have already created a Linked list.");
}
else
{ createnode();
a++;
}
break;
case 2: traverse();
break;
case 3: exit(0);
defalut: printf("Enter a valid choice\n");
}
}
}
0 Comments