数组式链表的c++实现

Array-style Linked list implementation C++

本文关键字:c++ 实现 链表 数组      更新时间:2023-10-16

我被分配了一个模拟链表结构的任务,但是使用的是节点数组而不是实际的链表。当我调用append函数时,我想检查我现有的数组是否已满,如果是,我想将数组大小增加一倍,并将我的Node附加到"list"(数组)的末尾。

我有麻烦加倍我的数组大小。

为了给你提供上下文,这里是我的一些。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: "数组类型'Node[4]'是不可分配的"

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

感谢。

你的代码中有几件事是不正确的:

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

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

...
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;
}

你会混淆数组和指针。变量free是一个常量指针,不能被重新赋值。如果需要修改其值,需要将Node free [4]修改为Node *free

C/c++ int[] vs int*(指针vs数组表示法)。有什么区别呢?