0
我原本不得不使用STL創建自己的鏈表。現在,我要實現一個複製構造方法,並且我很難理解它。在幾天內對此進行測試,所以我真的很想說清楚。 (測試是封閉的書,所以需要真的)。 該列表包含一個EmployeeNode指針*頭。 EmployeeNode包含一個Employee和一個指向下一個EmployeeNode的指針。 Employee類包含名稱和薪水。鏈接列表複製構造函數
當試圖複製第三個節點時,該方法似乎陷入for循環。我認爲這是因爲我覆蓋了newNode,但我不知道如何解決這個問題。
ListOfEmployee::ListOfEmployee(const ListOfEmployee &obj)
{
head = NULL;
if(obj.head != NULL)
{
EmployeeNode *newNode = new EmployeeNode("", 0);
EmployeeNode *tempPtr;
EmployeeNode *newPtr;
//using the temp pointer to scroll through the list until it reaches the end
for(tempPtr = obj.head; tempPtr->next !=NULL; tempPtr = tempPtr->next)
{
if(head == NULL)
{
cout<<"Attempts to initialize the head"<<endl;
head = newNode; //assinging the new node to the head
newNode->emp.name = tempPtr->emp.name;
newNode->emp.salary = tempPtr->emp.salary;
cout<<"Initializes the head"<<endl;
}
else
{
cout<<"Attempts to add a new node"<<endl;
//using the temp pointer to scroll through the list until it reaches the end
for(newPtr = head; newPtr->next !=NULL; newPtr = newPtr->next)
{
cout<<"Looping through the list"<<endl;
}
//assiging the last place to the new node
newPtr->next = newNode;
newNode->emp.name = tempPtr->emp.name;
newNode->emp.salary = tempPtr->emp.salary;
cout<<"Adds a new node"<<endl;
}
}
}
}
謝謝。現在看起來很明顯! – GermaineJason
另外,newNode-> next在EmployeeNode構造函數中初始化爲NULL。 – GermaineJason