Saturday, June 9, 2012

C program to delete last node of a doubly linked list


Insertion and deletion of nodes is very essential in data structure programs, whether it is linear linked list or doubly linked list is immaterial. We have seen that insertion or deletion programs on doubly linked lists are better than linear linked list in most of the cases. Exception insertion or deletion on specific location, traversal of the list is not required in doubly linked list.

We have seen that for deletion last node in linear linked list traversal is a compulsory. In doubly linked list the case is not the same. Here we have to simply access the last node address directly using the extreme right list pointer and connections to be set properly before deleting the last node of the doubly linked list.


# include < stdio.h>
# include < stdio.h>
struct list
{
char info[20];
struct list *next;
struct list *prev;
};
struct list *new1,*node;
void create(struct list *s,struct list *e)
{
char ch;
node=s;
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 string value:- ");
gets(node->info);
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 0x%x--%s", node,node->info);
node = node->next;
}
printf("\n");
}
void displayR (struct list *e,struct list *s)
{
node = e->prev;
while (node!=s)
{
printf("\n%s",node->info);
node = node->prev;
}
printf("\n");
}
void delL(struct list *e)
{
node=e->prev;
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 last location\n");
delL(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