数组式链表的c++实现
Array-style Linked list implementation C++
我被分配了一个模拟链表结构的任务,但是使用的是节点数组而不是实际的链表。当我调用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]'是不可分配的"
请给我一些更好的方法来做这件事。在线的所有解决方案似乎都适用于整数数组,但不适用于我的节点数组。
感谢。
你的代码中有几件事是不正确的:
- 你的
-
memcpy
命令以字节为单位接受大小,因此您需要乘以sizeof(Node)
。 - 也许这是有意的,但是
doubleSize()
方法是私有的。
free
属性是一个静态数组。在您的情况下,您需要一个动态的,具有适当的构造函数。下面是编译和运行的代码的更正版本:
...
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数组表示法)。有什么区别呢?
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的