Friday, 22 June 2012

write a menu driven program using c for signly linked list


/*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 firts position of linked list
-to delete a node in between by 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;
void create();
void display();
void first();
void del();
void 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 first position:");
printf("\n4 :delete a node in between by 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:first();
       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 first()
{
temp=malloc(sizeof(struct node));
printf("\nenter the number:-");
scanf("%d",&temp->data);
temp->next=start;
start=temp;
printf("\n\n");
}
void del()
{
int pos,i;
printf("\nenter the position which you want to delete:-");
scanf("%d",&pos);
count();
if(pos==1||pos==cnt||pos>cnt)
{
printf("\nyou enter wrong position");
}
else
{
q=start;
for(i=0;i<pos-2;i++)
{
q=q->next;
}
temp=q->next;
q->next=temp->next;
free(temp);
q=q->next;
printf("%d",pos);
}
}
void count()
{
q=start;
while(q!=NULL)
{
q=q->next;
cnt++;
}
}

No comments: