Tuesday, June 12, 2012

C program to delete the first node of a doubly linked list


Previously we have seen how to delete the last node of a doubly linked list. To delete the first node, no traversal is required. Simply connect the left header node with the second node of the doubly linked list to disconnect the node from the list and remove it.

Here is the program

# include < stdio.h >
# include < stdlib.h >
struct list
{
char ch;
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 any character:- ");
scanf(“%c”,&node->ch);
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--%c", node,node->ch);
node = node->next;
}
printf("\n");
}
void displayR (struct list *e,struct list *s)
{
node = e->prev;
while (node!=s)
{
printf("\n%c",node->ch);
node = node->prev;
}
printf("\n");
}
void delF(struct list *s)
{
node=s->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 Displaying the list from left to right\n");
displayL(start,end);
printf("\n Displaying the list from right to left\n");
displayR(end,start);
printf("\nFirst node deleted\n");
delF(start);
printf("\n now the list from left to right\n");
displayL(start,end);
printf("\nNow the list from right to left\n");
displayR(end,start);
getch();
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner