c++ - 数组式链表实现C++

标签 c++ dynamic nodes

我的任务是模拟链表结构,但使用节点数组而不是实际链表。当我调用我的附加函数时,我想检查我现有的数组是否已满,如果是,我想将数组大小加倍,并将我的节点附加到“列表”(数组)的末尾。

我无法将数组大小加倍。

为了给你上下文,这是我的一些 .h 文件:

...
const int NULL_INDEX = -1;

struct Node {
    char info;
    int next;
};

class LList1 {

private:
    Node free [4];

    // When more memory is called for, the array will double in size
    // returns true if reallocation of memory was successful
    bool doubleSize();
    .
    .
    .
}

这是我的 .cpp 文件中试图将数组大小加倍的部分:

bool LList1::doubleSize() {
    Node* newArray = new Node[this->length()*2];
    memcpy(newArray, free, this->length()*2);
    free = newArray;
    return true;
}

我也尝试过使用 realloc 和其他函数。我一直有同样的问题。 线路

"free = newArray" 

在 XCode 中一直给我这个错误:“Array type 'Node[4]' is not assignable”

请给我一些关于更好的方法的见解。所有在线解决方案似乎都适用于整数数组,但不适用于我的节点数组。

非常感谢。

最佳答案

您的代码中有几处不正确:

  1. 您的free 属性是一个静态数组。在您的情况下,您需要一个动态的,具有适当的构造函数。
  2. memcpy 命令采用字节大小,因此您需要乘以 sizeof(Node)
  3. 也许这是有意为之,但 doubleSize() 方法是私有(private)的。

这是编译和运行代码的更正版本:

...
const int NULL_INDEX = -1;

struct Node {
    char info;
    int next;
};

class LList1 {
public:
    LList1();
    ~LList1();
    int getLength();
    bool doubleSize();

private:
    int length;
    Node* free;

    // When more memory is called for, the array will double in size
    // returns true if reallocation of memory was successful
};

int LList1::getLength() {
    return this->length;
}

LList1::LList1() {
    this->free = new Node[4]; // Default size
    this->length = 4;
}

LList1::~LList1() {
    delete []this->free;
}

bool LList1::doubleSize() {
    Node* newArray = new Node[this->length*2];
    memcpy(newArray, free, this->length * sizeof(Node));
    free = newArray;
    this->length *= 2;
    return true;
}


int main(int, char **) {
    LList1 l;
    std::cout << "Original length: " << l.getLength() << std::endl;
    l.doubleSize();
    std::cout << "After doubling length: " << l.getLength() << std::endl;
    return 0;
}

关于c++ - 数组式链表实现C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39696505/

相关文章:

c++ - 为什么类中的initializer_list没有声明为 "const std::initializer_list & li"?

java - 从 C++ 访问 Java 类的最佳方式? (比直接使用 JNI 更好)

c++ - 使用虚拟纯函数访问字段的段错误

android - 如何动态地将android属性layout_alignParentBottom设置为按钮

html - 通过 html 设置 css 值?

javascript - 处理当前 <div> 处的所有 <span>,然后检查 <span> 属性的值

azure - 在 azure 服务结构上将节点类型(即可靠性层)设置为银牌到铜牌后,集群运行状况出现错误

c++ - 复杂对象的 MPI 共享内存

带类型提示的动态函数

java - 为什么这没有意义?删除节点