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

Copying elements from parameter list into a calling object?

本文关键字:调用 对象 复制 参数 列表 元素      更新时间:2023-10-16

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

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

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

这样做:

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节点。