/*write a menu driven program using c for signly linked list following
to perform operation
-to create list
-to display list
-to add a node at last position of linked list
-to delete a node from last position of linked list
*/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *next;
}*start,*q,*temp;
int cnt=0;
void create();
void display();
void last();
void del();
int count();
void main()
{
char ch='y';
int choice;
clrscr();
while(ch=='y'||ch=='Y')
{
printf("\n1 :to create list");
printf("\n2 :to display list");
printf("\n3 :add node at last position:");
printf("\n4 :delete a node fromlast position of list");
printf("\n\nenter your choice:-");
scanf("%d",&choice);
switch(choice)
{
case 1:while(ch=='y'||ch=='Y')
{
create ();
printf("\ndo you want to insert element(Y|N):-");
scanf("\n%s",&ch);
}
break;
case 2:
display();
break;
case 3:last();
break;
case 4:if(start==NULL)
printf("\nlinked list is empty");
else
del();
break;
}
printf("\n\ndo you want to enter another choice(Y|N):-");
scanf("\n%s",&ch);
}
getch();
}
void create()
{
temp=malloc(sizeof(struct node));
printf("\nenter the number:-");
scanf("%d",&temp->data);
temp->next=NULL;
if(start==NULL)
start=temp;
else
{
q=start;
while(q->next!=NULL)
{
q=q->next;
}
q->next=temp;
}
}
void display()
{
if(start==NULL)
printf("\nlinked list is empty");
else
{
printf("\nelement in singly linked list are:-\n");
q=start;
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->next;
}
}
}
void last()
{
int i;
q=start;
count();
if(cnt==0)
printf("linked list is empty");
else
{
for(i=0;i<cnt-1;i++)
{
q=q->next;
if(q==NULL)
{
printf("invalid position");
return;
}
}
temp=malloc(sizeof(struct node));
printf("\nenter the number:-");
scanf("%d",&temp->data);
temp->next=q->next;
q->next=temp;
}
display();
}
void del()
{
int pos,i,end;
q=start;
end=count();
if(end==0)
{
printf("\nlinked list is empty");
}
else
{
for(i=0;i<end-2;i++)
{
q=q->next;
}
temp=q->next;
printf("\nthe deleted elemet");
q->next=NULL;
free(temp);
printf("\n\n");
}
}
int count()
{
struct node *q=start;
cnt=0;
while(q!=NULL)
{
q=q->next;
cnt++;
}
return cnt;
}
No comments:
Post a Comment