Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

adding new nodes in a linked list while looping

linked list loop

  • Please log in to reply
2 replies to this topic

#1 emda321

emda321

    CC Lurker

  • Just Joined
  • Pip
  • 3 posts

Posted 17 June 2007 - 10:13 AM

hello everybody

i wanna creat a linked list,and the list is contained in a big loop.and i'm supposed to create new DIFFERENT nodes containg different information that can be accessed later during each iteration of the loop.i tried to dynamically allocate a new node each iteration and save the data and then delete the pointer.but strangely in the next iteration when i allocate the pointer again,it points to the previous node and overwrites its data so eventually i'll have one node only!!!..can u plz tell me why??

here's my code..


struct user * f;   //front pointer
f=NULL;
struct user * r;     //rear pointer
r=NULL;
struct user * temp;     //the temporary pointer that i use to allocate
temp=NULL;
int back;
back=1;
while(back==1)
{
if(f==NULL)     //first node to be added
   {
    temp=(struct user *)malloc(sizeof(struct user));    //user is my structure
   
    temp->link=NULL;                      //the link field to the following node
   stpcpy((temp->data1),input1);
   stpcpy((temp->data2),input2);
   f=temp;
   r=f;
   free(temp);
  
   }
   else
   {
    temp=(struct user *)malloc(sizeof(struct user));
   temp->link=NULL;
   stpcpy((temp->data1),input1);
   stpcpy((temp->data2),input2);
   r->link=temp;
   r=temp;
    free(temp);

    }
}


thanks alot...
  • 0

#2 v0id

v0id

    Retired

  • Retired Mod
  • PipPipPipPipPipPipPipPip
  • 2313 posts

Posted 17 June 2007 - 08:41 PM

I have made a complete example of using Linked List, that you may find interesting. You can eventually use it to see how it can be done.

You can find it on my homepage here:
v0id.dk
and a direct link here:
http://v0id.dk/fv/code/c/linked_list.c
  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

#3 emda321

emda321

    CC Lurker

  • Just Joined
  • Pip
  • 3 posts

Posted 17 June 2007 - 11:27 PM

thanks alot void,your program was really helpful to me..
  • 0





Also tagged with one or more of these keywords: linked list, loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download