Tuesday, June 12, 2012

C program to delete any node of a doubly linked list


Previously we have seen how to delete the last node and first node of a doubly linked list. In both the above cases no traversal was required. To delete any location node of a doubly linked list, traversal is required but unlike linear linked list only one moving pointer is needed here. This moving pointer in the doubly linked list will trace out the location and from that point the node will be disconnected from the doubly linked list and removed.

Here is the program

# include < stdio.h>
# include < stdio.h>
struct list
{
int age;
struct list *next;
struct list *prev;
};
struct list *new1,*node;
void create(struct list *s,struct list *e)
{
char ch;
node=s;
node->next = (struct list *) malloc(sizeof(struct list));
node->next->prev= node;
node = node->next;
node->next=e;
e->prev=node;
printf("\n Enter the numeric value:- ");
scanf("%d",&node->age);

printf("\nWant to create a node(y/n):");
ch=getche();
while (ch != 'n')
{
node->next = (struct list *) malloc(sizeof(struct list));
node->next->prev= node;
node = node->next;
printf("\n Enter the numeric value:- ");
scanf("%d",&node->age);
printf("\n Enter choice--'n' for break: ");
ch = getche();
}
node->next = e;
e->prev=node;

}
void displayL (struct list *s,struct list *e)
{
node = s->next;
while (node!=e)
{
printf("\n%d", node->age);
node = node->next;
}
printf("\n");
}
void displayR (struct list *e,struct list *s)
{
node = e->prev;
while (node!=s)
{
printf("\n%d",node->age);
node = node->prev;
}
printf("\n");
}
void delA(struct list *s,struct list *e)
{
int c=1,counter;
printf("\nEnter the location of the node to be deleted:");
scanf("%d",&counter);
node=s->next;
while(node->next!=e)
{
if(c==counter)
break;
c++;
node=node->next;
}
node->prev->next=node->next;
node->next->prev=node->prev;
free(node);
}
void main()
{
struct list *start,*end;
clrscr();
start=(struct list *) malloc(sizeof(struct list));
end=(struct list *) malloc(sizeof(struct list));
create(start,end);
printf("\n Created list is as follows(L ->R)\n");
displayL(start,end);
printf("\n Created list displayed from R->L\n");
displayR(end,start);
printf("\nDeleting the First node\n");
delA(start,end);
printf("\n now the listfrom L ->R\n");
displayL(start,end);
printf("\n list from R to L after deletion\n");
displayR(end,start);
getch();
}


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner