Suds2
Suds2

Reputation: 261

Can someone tell me if my logic is right for my function to add to a linked list?

I started a function to add a structure to a linked list. My prof wants us to add the structure alphabetically by last name and first name. I've been really confused lately on linked lists, so I was wondering if someone could tell my if I'm using the right logic or completely screwing up.

// Similar to hw06, you will be inserting into a list of students sorted by their last name.
// Similar to hw05, there may be students on the list that have the same last name.
// You will also be tested to assure that a student is not added to the list twice (same first name and last name).
// If a student already exists with the same last name, then you will need to sort them by their first names.
//
// If the student is already on the list, return the integer value 0.
// If the student is not on the list, add the student to the list and return the integer value 1.
//
// "list" is initialized as NULL. Use this as your 'head' of the list and insert into it accordingly.
// There are 4 possibilities for inserting into the list:
//  - inserting into an empty list
//  - inserting at the beginning of the list
//  - inserting inbetween 2 nodes in the list
//  - inserting at the end of the list
int add(struct student* new_student)
{
struct container* temp = list;
// Nothing is in the list yet
if(temp == NULL){
    temp->student = new_student;
    temp->next = NULL;
    list->next = temp;
    return 1;
}
else{

    // If the list is not empty
    while(temp->next != NULL){

        // If a last name in the list is the same as the last name of the new student
        if(strcmp(temp->student->lastName, new_student->lastName) == 0){

            // If the first name is the same
            if(strcmp(temp->student->firstName, new_student->firstName) == 0){
                return 0;
            }
            // If the first name is different
            else{
                // Sort by first name instead of last name
            }
        }
    }
}


}

Upvotes: 0

Views: 78

Answers (1)

R Sahu
R Sahu

Reputation: 206597

I see couple of problems in the if block.

// Nothing is in the list yet
if(temp == NULL) {

   // This is a problem
   // You enter this block when temp is NULL.
   // Setting temp->new_student and temp->next when temp is NULL
   // causes undefined behavior.
   temp->student = new_student;
   temp->next = NULL;

   // This is a problem
   // You enter this block when list is NULL.
   // Setting list->next when list is NULL causes undefined behavior.
   list->next = temp;

   return 1;
}

What you need is:

if(temp == NULL) {
   // Allocate memory for a new container.
   // Set the member data
   temp = malloc(sizeof(*temp));
   temp->student = new_student;
   temp->next = NULL;
   list = temp;
   return 1;
}

Upvotes: 1

Related Questions