F How to delete a specified node from a single link list? | CodeTheta

How to delete a specified node from a single link list?

April 17, 2014

/* http://native-code.blogspot.com */

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct link
{
int data;
struct link *next;
} node;
node *del_node_val(node*, int);
node *ins_beg(node*, int);
void display(node*);
void main()
{
int ch, x, k;
node *head=NULL;
while(1)
{
printf("/* http://native-code.blogspot.com */");
printf("\n\n1-->New node\n2-->Display\n3-->Node to delete\n4-->EXIT\n");
scanf("%d", &ch);
switch(ch)
{
case 1:
printf("Enter data of the new node:\n");
scanf("%d", &x);
head=ins_beg(head, x);
break;
case 2:
display(head);
printf("\n");
break;
case 3:
printf("Enter value of node to delete:\n");
scanf("%d", &k);
head=del_node_val(head, k);
break;
case 4:
exit(0);
default:
printf("Wrong choice.\n");
}
}
getch();
}
node *ins_beg(node *h, int x)
{
node *temp;
temp=(node*) malloc (sizeof(node));
temp->data=x;
temp->next=NULL;
if(h==NULL)
h=temp;
else
{
temp->next=h;
h=temp;
}
return(h);
}
void display(node *h)
{
while(h!=NULL)
{
printf("%d-->", h->data);
h=h->next;
}
printf("NULL");
}
node *del_node_val(node *h, int k)
{
node *d, *p;
d=h;
p=NULL;
if(d->data==k)
{
h=h->next;
free(d);
}
else
{
p=d=h;
while(d!=NULL)
{
if(d->data==k)
break;
else
d=d->next;
}
if(d==NULL)
{
printf("\nNode not found");
return(h);
}
else
{
while(p->next!=d)
p=p->next;
p->next=d->next;
free(d);
}
}
return(h);
}

/* http://native-code.blogspot.com */

Post a Comment