有人可以告诉我,我的逻辑是否适合我的功能添加到链接列表?

时间:2016-03-11 23:16:28

标签: c

我启动了一个将结构添加到链表的函数。我的教授希望我们按姓氏和名字的字母顺序添加结构。我最近对链接列表感到困惑,所以我想知道是否有人可以告诉我,如果我使用正确的逻辑或完全搞砸了。

// 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
            }
        }
    }
}


}

1 个答案:

答案 0 :(得分:1)

我在if块中看到了几个问题。

// 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;
}

您需要的是:

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;
}