Wednesday, June 6, 2012

C Program on insertion of new node at any location of doubly linked list


In my previous post, I have discussed about inserting a node at front and rear end of a doubly linked list. This is the continuation of inserting nodes in doubly linked list. In this program a new node will be inserted at user specified position any location.

# include < stdio.h >
# include < stdlib.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);
node->next = e;
e->prev=node;
printf("\n Enter choice--'n' for break: ");
ch = getche();
}
}
void displayL (struct list *s,struct list *e)
{
node = s->next;
while (node!=e)
{
printf(" 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(" 0x%x--%s", node,node->info);
node = node->prev;
}
printf("\n");
}
void insertA(struct list *s)
{
struct list *new1;
int c=1,count;
printf("\nEnter the location:");
scanf("%d",&count);
fflush(stdin);
new1 = (struct list *) malloc(sizeof(struct list));
printf("\nEnter the new value:");
gets(new1->info);
node=s->next;
while(node)
{
if(c==count)
break;
node=node->next;
c++;
}
node->prev->next=new1;
new1->prev=node->prev;
new1->next=node;
node->prev=new1;
}
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("\nInserting a new location at user specified location\n");
insertA(start);
printf("\n now the listfrom L ->R\n");
displayL(start,end);
printf("\n list from R to L after insertion\n");
displayR(end,start);
getch();
}

Steps taken for inserting node in doubly linked list at the user specified location.

 1. Allocate new node and enter data
2. Access the location where the new node is to be inserted, here traversal is required but unlike linear linked list only one moving pointer is used here for searching the location.
3. Set the next address pointer of the new node to point the next location of the node which the moving pointer is pointing.
4. Set the previous address pointer of next node to point the new node.
5. Set the next address pointer of node of the doubly linked list pointed by the moving pointer to point the new node.
6. Set the previous address pointer of the new node to point the node of the doubly linked list which is pointed by the moving pointer.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner