Hello guys.

I have to sort a linked list for an assignment alphabetically, but for some reason the last node to be sorted is left off when printed.
Player* insertPlayerInSortedOrderByName(Player* head, char* name, int goals, int assists){
	Player* newptr;
	newptr=createPlayer(name,goals,assists);
	
	if (head==NULL)
	{
		return newptr;
	}
	
	if (strcmp(head->name,newptr->name)>0){ //name in newptr goes before name in head pointer alphabetically
		newptr->next=head;
		head=newptr;
		return head;
	}
	Player* prev=head;
	Player* conductor=head->next;
	while(prev->next && strcmp(newptr->name, conductor->name) > 0){
	
		if(strcmp(newptr->name,conductor->name)<0){  //name in newptr goes between in names two player pointers.
			newptr->next=conductor;
			prev->next=newptr;
			return head;
		}
		conductor=conductor->next;
		prev=prev->next;
		
	}
	//newptr is placed at end of linked list if previous conditions aren't met 
	newptr->next=conductor; 
	prev->next=newptr;
	
	return head;
Unsorted list is
Redden 2 0
Berglund 5 2
Jackman 2 0
Stewart 4 0
Oshie 3 5
McDonald 2 4
Pietrangelo 2 7
Perron 2 6
Tarasenko 5 5

Printed sort comes out as
Berglund 5 2
Jackman 2 0
McDonald 2 4
Oshie 3 5
Perron 2 6
Pietrangelo 2 7
Redden 2 0
Stewart 4 0
Thanks in advance for your assistance. :)

Comments

  • I tested out your code, and it works fine.
    Chances are the error is either in your display code, or in the code that reads from the file (or whatever puts the things in the list)
  • The Dark wrote:
    I tested out your code, and it works fine.
    Chances are the error is either in your display code, or in the code that reads from the file (or whatever puts the things in the list)

    The error was in my print function. Thank you so much. I would stop printing when curr->next was null instead of curr==null
Sign In or Register to comment.