Monday 9 April 2012

Program in C to insert a node at first position in a given doubly linked list.

#include<stdio.h>

#include<conio.h>

#include<alloc.h>

#define null 0

void main()

{

struct dnode

{

struct dnode *prev;

int data;

struct dnode *next;

} *temp,*start,*end,*n;



int i;

char c;

clrscr();

start=end=null;

for(i=0;i<=1;i++)

{

if(start==null)

{

printf("enter data for the node:");

scanf("%d",&temp->data);

temp->next=null;

temp->prev=null;

start=temp;

end=temp;

}

else

{

while(1)

{

printf("are you want to add another node(y/Y):");

fflush(stdin);

scanf("%c",&c);

if(c=='y'||c=='Y')

{

n=(struct dnode*)malloc(sizeof(struct dnode));

printf("enter data for the node:");

scanf("%d",&n->data);

n->next=null;

n->prev=temp;

temp->next=n;

temp=n;

end=n;

}

else

break;

}

}

}



printf("the list you created is:\n");

temp=start;

while(temp->next!=null)

{

printf("%d\t",temp->data);

temp=temp->next;

}

printf("%d\n",temp->data);

printf("addition at first place\n");

{

n=(struct dnode *)malloc(sizeof(struct dnode));

printf("enter the data for the node:");

scanf("%d",&n->data);

n->prev=null;

n->next=start;

start->prev=n;

start=n;

}

printf("after operation list is:\n");

temp=start;

while(temp->next!=null)

{

printf("%d\t",temp->data);

temp=temp->next;

}

printf("%d\n",temp->data);

getch();

}



OUTPUT:

Enter data for the node:45

Are you want to create another node(y/Y):Y



Enter data for the node:65

Are you want to create another node(y/Y):n

The list you created

45 65

Addition at the first place

Enter data for the node:22

After operation list is: 22 45 65

No comments:

Post a Comment