链表C++ 使用突变器更新头部的下一个时不保存



我是C 的新手,并致力于设置链接列表。为什么下面的代码不更新列表的下一个。我得到以下输出

    void addToList(int dataToAdd){
        Node nodeToBeAdded(dataToAdd, NULL); //initilize the node we are going to add with the data that was given by the user
        if(this->getHead() == NULL){
            this->setHead(&nodeToBeAdded);
            cout << "Added " << this->getHead()->getData() << " to the head of the listn";
            return;
        }
       //Calls this even after I set the heads next
        else if(this->getHead()->getNext() == NULL){
            cout<<"Testn";
            this->getHead()->setNext(&nodeToBeAdded);
        }
        //IT NEVER REACHES THIS
        else{
            cout<<"super testn";
        }
    }

我得到以下输出

Added 3 to the head of the list
Test
Test

谢谢

从我所看到的,您当前的输出是正确的,并且根据当前代码进行了预期。我看到的主要问题是,您的添加代码在找到一个插入新节点的点时只能经过列表头的1-2步。您应该遵循的一般过程是走下列表,直到到达末端,然后在此处添加新节点。这样的东西:

void addToList(int dataToAdd) {
    Node* curr = this->getHead();
    Node nodeToBeAdded(dataToAdd, NULL);
    // for an empty list assign the head and return
    if (curr == NULL) {
        this->setHead(&nodeToBeAdded);
        cout << "Added " << this->getHead()->getData() << " to the head of the listn";
        return;
    }
    // otherwise walk down the list and insert the new node at the end
    while (curr->getNext() != NULL) {
        curr = curr->getNext();
    }
    curr->setNext(&nodeToBeAdded);
    return;
}

相关内容

最新更新