Skip to main content
gamedev.net
🔒 Locked

LL Help

Started by Tuggle Sep 16, 2005 at 5:40 AM 0 replies 550+ views
Original Post
Tuggle
Tuggle
Hello, I am trying to work on something that dynamically creates a linked list, all the tutorials I've seen show a way of doing it something like;

struct example {
  char *whatever
  struct example *next 
}; 

struct example *teststruct = malloc( sizeof( struct example ) ); 
teststruct->next = NULL; 
struct example *anotherstruct = malloc( sizeof( struct example ) ); 
teststruct->next = anotherstruct; 

and then to cycle through it, just do; 
teststruct = teststruct->next; 
However, if I have to go everywhere creating structures and linking them manually like that I don't really see a point. So I was thinking of writing something that does this for me. Like;
 
struct example {
   char *whatever;
   struct example *next;
};

//Create nodes 
void crea_node( struct example *tempstruct, int numnode )
{
   for( int a = 0; a < numnode; a++, tempstruct = tempstruct->next ) {
      struct example *creanode = malloc( sizeof( struct example ) );
      tempstruct->next = creanode; 
   }
}

int main( void ) 
{
   struct example lamestruct; 
   crea_node( &lamestruct, 5 ) // 5 linked lists
   
   return 0; 
}
Please note that was just a rough example, so of course syntax and things might be off. My question would be can something be created which roughly accomadates this idea? Doesn't have to be this exact implementation.
ZedFx
ZedFx
struct LL{	// your stuff	LL * next;	LL * prev;};int LL_add(LL * ll, unsigned int count = 1){	if (ll == NULL)	{		return 0;	}	if (count != 0)	{		LL * llstart = (LL *)malloc(sizeof(LL));		LL * llend = llstart;		for (count --; count > 0; count --)		{			llend->next       = (LL *)malloc(sizeof(LL));			llend->next->prev = llend;			llend             = llend->next;		}		llstart->prev = ll;		llend->next   = ll->next;		ll->next      = llstart;	}	return 1;}int LL_rem(LL * ll, unsigned int count = 1){	if (ll == NULL)	{		return 0;	}	for (; count > 0; count --)	{		LL * llrem;		if (ll->next != NULL)		{			llrem = ll;			ll    = ll->next;		}		else if (ll->prev != NULL)		{			llrem = ll;			ll    = ll->prev;		}		else		{			return 0;		}		if (llrem->next != NULL)		{			llrem->next->prev = llrem->prev;		}		if (llrem->prev != NULL)		{			llrem->prev->next = llrem->next;		}		free(llrem);	}	return 1;}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.