Trying to print a linked list, but the first item is the only thing that prints. I've played around with it, and I cannot figure out whether it is my print function, or my construction of the list that is causing this.
This is my construction.
Code:
Player* open( FILE *fp ){
int i, lines;
char hold[ MAX_LINE ] = { 0 };
char* token = NULL;
const char space[] = " ";
const char nLine[] = "\n";
Player* head = NULL;
char name[ MAX_NAME ] = { 0 };
int goals;
int assists;
lines = countLines( fp );
/* Tokenize the strings in the file and pass them to link. */
for( i = 0; i < lines; i++ ){
fgets( hold, MAX_LINE, fp );
token = strtok( hold, space );
strcpy( name, token );
token = strtok( NULL, space );
goals = atoi( token );
token = strtok( NULL, nLine );
assists = atoi( token );
/* In the first iteration, head is NULL, thus the newly created node will be the head
* of the list. We are returning to head because we are not passing head by reference. */
head = link( head, name, goals, assists );
if( token == NULL ){
break;
}//endif
}//endfr
return head;
}//endfn
Player* link( Player* x, char name[], int goals, int assists ){
Player* current = x; // Set our record pointer to the passed node.
/* We are calling createRecord to malloc and assign pertinant data to the node. */
Player* newPlayer = createPlayer( name, goals, assists );
/* Now we check to see if the list is empty. */
if( x == NULL ){
return newPlayer;
}else{
while( current != NULL ){
current = current->next;
}//endwh
current = newPlayer;
}//endel
return x;
}//endfn
Where createPlayer simply mallocs and assigns pertinent data to created node, then returns the pointer to the node.
This is my print function.
Code:
void printPlayers( Player* head ){
Player* x = head;
if( x == NULL ){
printf("\n\nThe list is empty!\n");
}else{
printf("\nName Goals Assists");
while( x != NULL ){
printf("\n%s %5d %10d", x->name, x->goals, x->assists );
x = x->next;
}//endwh
}//endel