Friday 8 March 2013

Implement the following basic operations on a singly linked list: a) Insertion at the front b) Insertion at the rear c) Insertion at an arbitrary position in the list


/*Program of singly linked list*/
#include<stdio.h>
#include<malloc.h>

struct node /*linked list’s node structure*/
{
     int info; /*for data*/
     struct node *link; /*self referenced pointer*/
}*start;
/*function for insertion at the front end*/
insert_front(int data)
{

     struct node *tmp;
     tmp=malloc(sizeof(struct node));
     temp->info=data;
     temp->link=start;
     start=tmp;
}/*End of insert_front()*/

/*function for insertion at rear end*/
insert_rear(int data)
{
     struct node *tmp,*q;
     q=start;
/*go to last node*/
     while(q!=NULL)
     {
          q=q->link;
     }/*end of while*/
     tmp=malloc(sizeof(struct node));
     tmp->link=NULL;
     tmp->info=data;
     q->link=tmp;
}/*End of inser_rear()*/

/*function for insertion at arbitrary position in list*/
insert_arbitrary(int data, int pos)
{
     struct node *tmp,*q;
     int i;
     q=start;
/*check for position*/
     for(i=0;i<pos;i++)
     {
          q=q->link;
          if (q==NULL);
          {
              printf(“There are less than %d elements”,pos);
              return;
}
     }/*End of for*/
     tmp=malloc(sizeof(struct node));
     tmp->link=q->link;
     tmp->info=data;
     q->link=tmp;
}

/*main() function */
{
     int choice,n,m.position,I;
     start=NULL;
     while(1)
     {
          printf(“1. Insert at front end\n”);
          printf(“2. Insert at rear end\n”);
          printf(“3. Insert at arbitrary pisition\n”);
          printf(“4. Exit”);
}/*end of while*/
     printf(“Enter Your Choice : “);
     scanf(“%d”, &choice);
     switch(choice)
     {
     case 1:
          printf(“Enter the element :”);
          scanf(“%d”, &m);
          insert_front(m);
          break;
     case 2:
          printf(“Enter the element :”);
          scanf(“%d”, &m);
          insert_rear(m);
          break;
     case 3:
          printf(“Enter the element :”);
          scanf(“%d”, &m);
printf(“Enter the position after which the element is inserted :”);
          scanf(“%d”, &position);
    
          insert_arbtrary(m,position);
          break;
     case 4:
          exit();
     default:
          printf(“Wrong choice\n”);
     }/*end of switch*/
}