Sunday, September 22, 2013

Wap to perform Single Linked List Operations.


#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
};
struct node *start;

int ins_beg()
{
struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));
printf("\n Enter the element:");
scanf("%i",&new_node->info);
if(start==NULL)
{
    new_node->link=NULL;
    start=new_node;
}
else
      {
            new_node->link=start;
            start=new_node;
      }
printf("\n Element Inserted sucessfully.\n");
main();
}
int ins_end()
{
    struct node *new_node,*lp;
new_node=(struct node*)malloc(sizeof(struct node));
printf("\n Enter the element:");
scanf("%i",&new_node->info);
if(start==NULL)
{
    new_node->link=NULL;
    start=new_node;
}
else
      {
            lp=start;
            while(lp->link!=NULL)
            {
                  lp=lp->link;
            }
            lp->link=new_node;
            new_node->link=NULL;
      }
printf("\n Element Inserted sucessfully.\n");
main();
}
int ins_pos()
{
struct node *new_node,*tptr;
int pos,i=0;
printf("\n Enter the position:");
scanf("%i",&pos);
if(pos==1)
    {ins_beg();
    main();}
else
{
tptr=start;
for(i=1;i<(pos-1)&&tptr!=NULL;i++)
    tptr=tptr->link;
if(tptr==NULL)
{printf("\n Invalid Position.");
    main();}
    else
    {   new_node=(struct node*)malloc(sizeof(struct node));
        printf("\n Enter the element:");
        scanf("%i",&new_node->info);
        new_node->link=tptr->link;
        tptr->link=new_node;
        printf("\n Item Inserted Sucessfully.");
        main();
    }
}
main();
}
int disp()
{
struct node *t;
if(start==NULL)
   {

    printf("\n List is empty.");
    return;
   }
t=start;
printf("\n Elements are:");
while(t!=NULL)
{
    printf("\n\n%i",t->info);
    t=t->link;
}
main();
}
int del()
{
int pos;
struct node *tptr,*ptr;
ptr=start;
printf("\n Enter the Position::");
scanf("%d",&pos);
if(pos==1)
{
 start=start->link;
}
else
{  int i=0;
    while(i<pos-1 && ptr!=NULL)
    {
        tptr=ptr;
        ptr=ptr->link;
        i++;
    }
    tptr->link=ptr->link;
}
main();
}


int main()
{
    do
    {
    int c,d;

    printf("\n\t\t Single Linked List Operations. \n 1.Insert \t 2.Delete \t 3.Display \t4.Exit.\n\n Enter Your Choice:");
    scanf("%d",&c);
    switch(c)
    {
    case 1:printf("\n\t Insert Operations\n\t 1.Begining \t 2.End \t 3.At a given position\nEnter your choice:");
           scanf("%d",&d);
           switch(d)
           {
               case 1:ins_beg();break;case 2:ins_end();break;case 3:ins_pos();break;default:printf("\n Wrong Choice.!!!");main();break;
           }

case 2:del();break;
case 3:disp();break;
case 4:exit(1);break;
default:printf("Wrong Choice!!!!\n");break;
    }
    }while(1);

    return 0;

}

No comments:

Post a Comment