Tuesday, September 23, 2008

Simle programme : How to add a node in a linklist

This is brief programme to add a node in a link list:


#include
#include
#include

struct node
{
int val;
struct node * next;
};



main()
{

node *h1,*h2,*head;
int a=1;
head=(node*) malloc(sizeof(node));
head->next=NULL;


h1=head;


while(1)
{
printf("\n\nif you want to enter values press 1");
scanf("%d",&a);
if(a!=1)
{
break;
}

h2=(node*) malloc(sizeof(node));

printf("\n\nEnter the value of the node\t");

scanf("%d",&h2->val);
h2->next=NULL;


h1->next=h2;
h1=h1->next;


}
h1=head;


/* ------------ PRINT THE LIST---------------*/

printf("\n List is ");

while(h1->next!= NULL)
{
h1=h1->next;
printf("\n%d",h1->val);
}




/* insertion */
h1=head;
int srch;
node *ins=(node*) malloc(sizeof(node));

printf("\n\nthe value you want to enter ");
scanf("%d",&ins->val);
printf("\n\n before which node u wanna enter\n\n");
scanf("%d",&srch);

while(h1->next->val!=srch)
{
h1=h1->next;
}

ins->next=h1->next;
h1->next=ins;


/* ------------ PRINT THE LIST---------------*/
h1=head;
printf("\n List is ");

while(h1->next!= NULL)
{
h1=h1->next;
printf("\n%d",h1->val);
}

}

Read more...

Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP