Friday, June 1, 2012

C Program on inserting new node at first location of linked list


Dynamic insertion and deletion of nodes in a linked list is very common. In previous posts, we have done programs on creating linked list, searching linked list. Today I will show how to insert a new node in a linked list at the first location.

 # include < stdio.h>
# include < stdlib.h>
struct link
{
int info;
struct link *next;
};
int i;
int number;
struct link *p, *new1;

void create(struct link *n)
{
char ch;
p=n;
printf("\n Enter choice ‘n’ for break: ");
ch = getche();
i = 1;
while(ch != 'n')
{
p->next = (struct link* ) malloc(sizeof(struct link));
p = p->next;
printf("\n Input the node: %d: ", (i+1));
scanf("%d", &p->info);
p->next = NULL;
printf("\n Input choice n for break: ");
ch = getche();
i++;
}
}
struct tag *insertion(struct link *n)
{
p=n;
new1 = (struct link* ) malloc(sizeof(struct link));
printf("\n Input the fisrt node value: ");
scanf("%d", &new1->info);
new1->next=p;
return new1;
}
void display(struct link *n)
{

p=n;
printf("\nNow displaying the current linked list:-\n");
while(p)
{
printf("%d\n",p->info);
p=p->next;
}
}
void main()
{
struct link *list;
clrscr();
list = (struct link *) malloc(sizeof(struct link));
printf("\nEnter the value :-");
scanf("%d",&list->info);
list->next=NULL;
create(list);
list=insertion(list);
display(list);
getch();
}

Technical analysis of this program

 In this program also the first node is created in the main () function and the address of the first node is passed to another function ‘void create(struct link *n)’ to create the linked list in a dynamic manner.

The program deals with insertion of new node in first location of the linked list. List pointer of the linked list have to change its value, so the insertion job is performed with a return type function. Function ‘struct tag *insertion(struct link *n)’ is used for this inserting job. Address of the first node of the linked list is passed to the function, this address is assigned on the next address pointer of the new node and the address of new node is returned to main () function.

The third function used here is ‘void display (struct link*)’ to display the linked list.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner