C++ 如何创建链接列表的拷贝作为类对象?

标签 c++

我正在尝试使用 LinkedList 类的 duplicate() 方法制作链接列表的拷贝。我整天都在为如何使这种方法起作用而绞尽脑汁。

duplicate 方法需要精确复制列表,返回指向新列表的指针。我希望能够在新列表上调用 LinkedList 方法。我应该返回一个 LinkedList 指针吗?还是节点指针?我觉得我在这里完全缺少一些简单的东西。

我什至如何将新头节点的位置存储在 LinkedList 指针中?

//LinkedList.h
#pragma once

#include<string>

using namespace std;

struct Node {
    string nodeData;
    Node* nextNode;
};

class LinkedList {
public:
    LinkedList();

    ~LinkedList();

    bool insert(string givenData);

    bool remove(string givenData);

    void print() const;

    int count() const;

    int find(string givenData) const;

    bool removeAll();

    LinkedList* duplicate() const;

private:
    Node* head;
};


//LinkedList.cpp duplicate() method
LinkedList* LinkedList::duplicate() const {
    LinkedList* newList;
    Node* newHeadNode = new Node;
    Node* newNode = new Node;

    newHeadNode->nodeData = head->nodeData;
    newHeadNode->nextNode = head->nextNode;

    Node* currentNode = head->nextNode;
    Node* previousNode = head;

    while ((currentNode) && (newNode->nodeData > currentNode->nodeData)) {
        previousNode = currentNode;
        currentNode = currentNode->nextNode;

        newNode->nextNode = previousNode->nextNode;
        previousNode->nextNode = newNode;
    }
}

最佳答案

首先,您混淆了指针和数据的作用。

所有节点都有到下一个节点的“链接”。如果你想复制一个列表,你想创建每个节点的拷贝,并连接它们。这意味着您不应将新节点连接到旧节点,而应仅连接它们之间的新节点。

newHeadNode->nextNode = head->nextNode; 因此是错误的。

此外,您的类有一个插入方法,您可以使用它,并且可能已经正确地创建了一个节点并设置了旧的尾节点指针。

你的函数体应该是这样的

LinkedList* LinkedList::duplicate() const {
    // create a new list
    LinkedList* newList = new LinkedList();
    // start from the first node of the old list
    currnode = this->head;

    // until currnode is valid
    while(currnode){
        // insert the data in the new list (the new list will deal with the pointers)
        newList->insert(currnode->data);
        // go to the next node of the old list
        currnode = currnode->nextNode;
    }

    return newList;

}

关于C++ 如何创建链接列表的拷贝作为类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44211730/

相关文章:

c++ - 了解继承多个空类时 gcc/clang 与 msvc2015 之间的不同填充规则

c++ - std::is_function 是如何实现的?

c++ - 为什么 C++ 方法不应该返回取消引用的指针?

c++ - 读取 RSysLog tcp 消息

c++ - 如何读/写或迭代 std::array 中特定范围的元素?

c++ - 使用 isalpha() C++ 的问题

c++ - 从 STL 列表中删除项目

c++ - C++ 的箭头 (->) 运算符的正式名称是什么?

c++ - clang:强制循环展开特定循环

等待用户 IO ('getchar()' 的 c++ 线程在主进程中挂起 'Py_Initialize()'