2016-09-26 165 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; 
}