Tuesday, 20 March 2018

Deletion of first node in Singly Linked List

In a simple linked list i.e is a part of a linear data structure we will know about how to delete the element in a linked list at a first node.
So, here the code for the deletion of first node in the linked list.


/*Pre-Processors*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>

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

/*funtions to create a linked list , display , and delete the first node */
void create(struct node **);
void display(struct node *);
void delfirst(struct node **);

void main()
{
struct node *head=NULL;
int i,num, dlf;
clrscr();
printf("\n\tEnter no. of elements:- ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
create(&head);
}
printf("\n\tDo you want any deletion at first (1--> YES And 0-->NO):- ");
scanf("%d",&dlf);
if(dlf==1)
{
delfirst(&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("\n\n\tEnter value:- ");
scanf("%d",&temp->data);
temp->ref=NULL;
*q=temp;
}
else
{
r=(struct node *)malloc(sizeof(struct node));
printf("\n\tEnter 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 delfirst(struct node **q)
{
struct node *dlf;
int temp;
dlf=*q;
temp=dlf->data;
*q=dlf->ref;
free(dlf);
}


No comments:

Post a Comment