2016-09-26 166 views
0

我给出了一个模拟链表结构但使用节点数组而非实际链表的任务。当我调用我的append函数时,我想检查我的现有数组是否已满,如果是,我想将数组大小加倍,并将我的节点追加到“list”(数组)的末尾。Array-style链接列表实现C++

我无法加倍我的数组大小。

为了让您的上下文,这里是我的我的一些.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此错误:“数组类型‘节点[4]’不分配”

请给我一些洞察到一个更好的方式做这个。所有在线解决方案似乎都适用于整数数组,但不适用于我的数组节点。

非常感谢。

+0

'Node free [4];'是不是一个可调整大小的数组。还有'new Node [this-> length()* 2];'返回一个指向新分配数组的指针。 'free'不是可以重新分配的指针 – PRP

+0

这对于'int'数组也不起作用;你必须为这些做不同的事情。你的成员需要成为一个指针。 – molbdnilo

+0

你所描述的更像是一个动态大小的数组([vector](http://en.cppreference.com/w/cpp/container/vector)),而不是一个链表。 –

回答

1

几件事情是在你的代码不正确:

  1. free属性是一个静态数组。在你的情况下,你需要一个动态的,具有适当的构造函数。
  2. memcpy命令的大小以字节为单位,因此您需要乘以sizeof(Node)
  3. 也许它是有意的,但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; 
}