Friday, 23 March 2018

Deletion in Singly linked list at given point

In a linear data structure linked list is a basic program while study about Data Structure.
 So, this time we gonna do "Deletion in linked list at given position/ point"

/*Pre Processors used throughout the program*/
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<stdlib.h>

/*structure of the node*/
struct node
{
int data;
struct node *ref;
};

/*function is created to handle program*/
void create(struct node **);
void display(struct node *);
void dellast(struct node**, int );

void main()
{
struct node *head=NULL;
int num,i,l,pos;
clrscr();
printf("\n\tEnter no. of element you want to insert:- ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
create(&head);
}
printf("\nDo You want any (1-->Yes and 0-->No):- ");
scanf("%d",&l);
if(l==1)
{       printf("\nEnter the position for the deletion :- ");
scanf("%d",&pos);
dellast(&head,pos);
}
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 *q)
{
while(q!=NULL)
{
printf("\n\tOUTPUT:- %d",q->data);
q=q->ref;
}
}


void dellast(struct node **q, int pos)
{
int i;
struct node *next;
struct node *temp=*q;
if(*q==NULL)
{
return;
}

if(pos==0)
{
*q=temp->ref;
free(temp);
return;
}
for( i=1;temp!=NULL && i<pos-1;i++)
{
temp=temp->ref;
}
if(temp==NULL || temp->ref==NULL)
{
return;
}
next=temp->ref->ref;
free(temp->ref);
temp->ref=next;

}


No comments:

Post a Comment