0

When Trying to add a Student to the end of my List it comes out to be in the wrong alphabetical order. I have tried changing the add to end part of my function but can't seem to see what's wrong.

This is the way I add to end

  Student *prvPtr= headStudentList;
    for(Student *curPtr = headStudentList->next; curPtr != NULL; curPtr = curPtr->next)
    {
            if (curPtr->next==NULL){
                    curPtr->next= newPtr; //newPtr
                    return headStudentList;
            }
             if(strcmp(curPtr->lastName,last)<0 ){ //change from first

                    if(strcmp(curPtr->firstName,first)<0 )
                    {
                    newPtr->next=curPtr->next;
                    curPtr->next =newPtr; //curPtr->next =newPtr
                    return headStudentList; //headStudentList
                    }
             }
    }

This is what is inside of the structs

typedef struct _grade {
char name[4];
double value;
struct _grade *next;} Grade;

////////////////////////////////////////////////////////////////////////////////////////

typedef struct _student {
char *lastName;
char *firstName;
Grade *headGradeList;
struct _student *next;} Student;
  • See https://stackoverflow.com/questions/53380109/linked-list-c-programming-error-by-inserting-new-element/53380533#53380533 for an implementation of a linked list. – Swordfish Nov 30 '18 at 03:49
  • 1
    That's an awful short `name` (3-chars + `'\0'`) Please provide [**A Minimal, Complete, and Verifiable Example (MCVE)**](http://stackoverflow.com/help/mcve). – David C. Rankin Nov 30 '18 at 03:57
  • The name is just an identifier ie Q10 and not the actually student name the students name is char lastName and char firstName – Nathan Barry Nov 30 '18 at 04:02
  • It is unusual to see string compares in code that manages a link list insertion or deletion. Also see [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – jww Nov 30 '18 at 09:23

1 Answers1

0

One thing i see is that you are skipping the first member of your linked list when you initialize your pointer in your for() loop. What if your list is empty? This wont add a node to the end.

Dauie
  • 86
  • 5