将参数列表中的元素复制到调用对象中?

时间:2016-09-23 03:59:38

标签: c++ linked-list

给定一个非空的单链表,该函数将参数列表中的所有元素复制到调用对象中。

void AnyList::preFour(const AnyList& otherList) {

    bool found = false;

    Node* checkPtr = otherList.ptrToFirst;

    //find first 4
    while (checkPtr != nullptr && !found) {

        if (checkPtr->getData() == 4) {
            found = true;
        }
        else 
            checkPtr = checkPtr->getPtrToNext();
    }


    Node* current = ptrToFirst;
    Node* copy = otherList.ptrToFirst;

    while (current != checkPtr) {


        current = current->getPtrToNext();
        copy = copy->getPtrToNext();
    }
}

这是我到目前为止的代码,我只需要一些关于如何在将这些元素复制到调用对象(空列表)时将参数列表复制到一定程度的指针。我需要创建一个新节点吗?

1 个答案:

答案 0 :(得分:0)

这样做:

void AnyList::preFour(const AnyList& otherList) {

    bool found = false;

    Node* checkPtr = otherList.ptrToFirst;

    //find first 4
    while (checkPtr != nullptr && !found) {

        if (checkPtr->getData() == 4) {
            found = true;
        }
        else 
            checkPtr = checkPtr->getPtrToNext();
    }

    Node* current;
    Node* copy = otherList.ptrToFirst;


    /* This node is just to facilitate in copying. 
       It actually stores no relevant data. 
       It will be deleted after we are done with copying.*/
    Node* dummy = new Node(); 
    current = dummy;

    while (copy != checkPtr) {

        Node* temp = new Node();
        current->next = temp; // Use appropriate method to set nextptr
        current = current->getPtrToNext();

        *current = *copy; // Use appropriate copy constructor or other method
        copy = copy->getPtrToNext();
    }
    /* This method should return NULL if next pointer is not available.
       If that is not so, just add a check here. 
    */
    ptrToFirst = dummy->getPtrToNext();
    delete dummy;
}

由于调用对象的列表为空,我们首先需要为第一个节点分配空间。所以我先创建一个dummy节点:

    Node* dummy = new Node();
    current = dummy;

虽然我们没有达到停止条件,但我们使用此循环将内容从参数列表复制到调用对象的列表。每次条件成功时我们都必须创建一个新节点。这是因为我们必须为复制新元素分配空间。:

    while (copy != checkPtr) {

        Node* temp = new Node();
        current->next = temp; // Use appropriate method to set nextptr
        current = current->getPtrToNext();

        *current = *copy; // Use appropriate copy constructor or other method
        copy = copy->getPtrToNext();
    }

请注意,复制后,我将ptrToFirst分配为dummy->getPtrToNext(),然后delete dummy节点。