Thursday, 15 March 2018

ALL Case of Deletion in Linked List

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>

struct node
{
int data;
struct node *ref;
};

void create(struct node **);
void display(struct node *);
void del(struct node **);

void main()
{
struct node *head=NULL;
int i,num;
clrscr();
printf("\nEnter no. of elements for your node:- ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
create(&head);
}
        del(&head);
        display(head);
        getch();
  }

void create(struct node **q)
{
struct node *temp, *r;
temp=*q;
if(*q==NULL)
{
temp=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value:- ");
scanf("%d",&temp->data);
temp->ref=NULL;
*q=temp;
}
else
{
r=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value:- ");
scanf("%d",&r->data);
r->ref=NULL;
while(temp->ref!=NULL)
{
temp=temp->ref;
}
temp->ref=r;

}

}

void display(struct node *p)
{
while(p!=NULL)
{
printf("\nOUTPUT:- %d",p->data);
p=p->ref;
}
}

void del(struct node **q)
{
struct node *temp , *old ;
int i,j=0;
temp = *q ;
old = temp ;
printf("\n\nEnter the number of position of element which you want to delete :   ");
scanf("%d",&i);

if(*q!=NULL && i==1)
{
old = old->ref ;
temp = old ;
*q = temp ;
}
      if(*q==NULL)
      {
old = old->ref;
temp = old ;
*q = temp ;
      }
      else
      {
while(j<i)
{
j++ ;
old = old->ref ;
if(j==i-1)
break ;
temp = temp->ref ;
}
temp->ref = old->ref ;
       }
}




No comments:

Post a Comment