我一直在試圖弄清楚我出錯的地方。我的add方法不檢測同一個學生是否添加了兩次。 P.s列表指向容器的頭部。C++添加方法邏輯
int add(Student* s)
{
Container *follow = list;
Container *newNode = new Container;
newNode->student = s;
if (list == NULL)
{
newNode->next = NULL;
list = newNode;
//cout << "Student Added!";
return 1;
}
else if (s->getFirstName().compare(list->student->getFirstName()) == 0) //duplication check
{
if (s->getLastName().compare(list->student->getLastName()) == 0) //Same Student
{
free(newNode->student); //Memory Mangment
free(newNode);
// cout << "Student Exist!";
return 0;
}
}
else //adding at the beginning of the list
{
newNode->next = list;
list = newNode;
// cout << "Student Added!";
return 1;
}
Container* temp = list->next;
while (temp != NULL) // inserting inbetween 2 nodes in the list
{
if (s->getFirstName().compare(list->student->getFirstName()) == 0)
{
if (s->getLastName().compare(list->student->getLastName()) == 0) //Same Student
{
free(newNode->student); //Memory Mangment
free(newNode);
// cout << "Student Exist!";
return 0;
}
}
else
{
newNode->next = list;
list = newNode;
// cout << "Student Added!";
return 1;
}
follow = temp;
temp = temp->next;
}
follow->next = newNode; // inserting at the end of the list
return 1;
}
我修改了下面的代碼,但我仍然收到運行時錯誤。
Container* follow = list;
Container* newNode = (Container*) malloc(sizeof(Container));
newNode->student = s;
newNode->next = NULL;
if (list == NULL) // inserting into an empty list
{
list = newNode;
return 1;
}
while (list != NULL)
{
if (search(s) == NULL)
{
newNode->next = list;
list = newNode;
return 1;
}
else if (search(s) != NULL)
{
free(newNode->student); //Memory Mangment
free(newNode);
// cout << "Student Exist!";
return 0;
}
}
以下是搜索的執行情況 //此功能已經爲您執行。如果請求的學生不在列表中,則返回NULL。
Student* search(Student* s)
{
Container *traverser = list;
while (traverser != NULL)
{
if (traverser->student->getFirstName() == s->getFirstName() && traverser->student->getLastName() == s->getLastName())
return traverser->student;
traverser = traverser->next;
}
return NULL;
}
Re'_CONTAINER_H_'請注意,以下劃線和大寫字母開頭的標識符保留給實現。 –
而不是'比較'調用,對於'std :: string',你可以使用'=='。 –
在C++ 11之後,而不是'NULL',一般的首選是使用'nullptr':這就是它的原因,即使我們已經有了'NULL',爲什麼它被引入。 –