2013-11-22 147 views
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; 
      } 
     } 
    } 
} 

回答

1

在你的代码,你在newPtr->next = newNode;你基本上是用以前分配的节点加入newNode。您应该使用new创建一个新节点。例如:

newPtr->next = new EmployeeNode("", 0); 
newNode = newPtr->next; 
newNode->emp.name = tempPtr->emp.name; 
newNode->emp.salary = tempPtr->emp.salary; 

另外,您应该在代码中设置newNode->next = NULL;

+0

谢谢。现在看起来很明显! – GermaineJason

+0

另外,newNode-> next在EmployeeNode构造函数中初始化为NULL。 – GermaineJason