New Android apps UniqueKey

Saturday 21 March 2015

Simple Linked list Program

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

struct node
{
 int data;
 struct node *link;                 //to creating self reference pointer
};

int display(struct node *,int);
void insertion(struct node *,int);
void deletion(struct node *,int);

struct node *head;
int count=0;

main() 
{
   int i,choice,inst=0,del,chk1=1,chk=1,num;
  
   do
   {
   printf("\nMENU:\n\n 1.Insertion\n 2.Deletion \n 3.Display\n 4.Exit\n\nenter your choice :     ");
   scanf("%d",&choice);
   
   switch(choice)
   {
  case 1:
          if(count==0)
          { 
           printf("\nThis is First Node\n"); 
          head=(struct node *)malloc(sizeof(struct node));
           insertion(head,inst);
          }
         else
         {
           printf("Where do you want to insert data\n 1. In starting \n2. End\n");
           scanf("%d",&inst);
           insertion(head,inst);
         }   
         break;
         
  case 2:
          printf("from where do you want to delete\n 1. In starting 2. End\n");
          scanf("%d",&del);
          deletion(head,del);
          break;
          
  case 3:
         chk1=display(head,count);
         if(chk1==1)
         printf("NULL\n");
         break;
         
  case 4:
          chk=0;
          break;
     
    default : printf("invalid option selected\ntry again\n\n");        
   }
 }
 while(choice!=4);
  }
  
void insertion(struct node *list,int num)
{ 
  struct node *new1;
  int num1;
  
  printf("Enter the number\n");
  scanf("%d",&num1);
  
  if(count==0&&num==0)
  {
    head->data=num1;
 head->link=NULL;
  }
  else if(num==1&&count>0)
  {
 new1=(struct node *)malloc(sizeof(struct node));
 new1->data=num1;
 new1->link=head;
 head=new1;
  }
  else if(num==2&&count>0)
  {
 for( ; ;)
 {
   if(list->link!=NULL)
      list=list->link;
   else
  {
    new1=(struct node *)malloc(sizeof(struct node));
    new1->data=num1;
    list->link=new1;
    new1->link=NULL;
    break;
  }
 }
  }
  
 count++;
 
}

void deletion(struct node *list,int num)
{
  struct node *temp;
  
  if(num==1&&count>0)
 {
   head=list->link;
   free(list);
 }
  else if(num==2&&count>1)
 {
   for( ; ;)
    {
  if(list->link->link!=NULL)
     list=list->link;
  else
   {
     free(list->link);
     list->link=NULL;
   break;
    }
   }
 }
 else if(count==1)
   free(head);
 else if(count<=0)
 {
    printf("List is empty\n\n"); 
    count--; 
 }
 count--;
 
}

int display(struct node *list,int num)
{ 
  int chk=1;
  
  if(num>0)
   {
  printf("%d->",list->data);
  num--;
  display(list->link,num);
   }
  else if(count<=0)
 {
   chk=0;
   printf("list is empty\n\n");
 }
 return(chk);
}

No comments:

Post a Comment