c++ - 使用数组上的链表排序索引列表
问题描述
我有一个项目使用数组上的单链表来实现排序索引列表。当我尝试执行添加功能时,我遇到了一些问题。这就是我的构造函数的样子:
SortedIndexedList::SortedIndexedList(Relation r) {
this->cap = 10;
this->elems = new TComp[this->cap];
this->next = new TComp[this->cap];
this->head = -1;
for (int i = 0; i < this->cap - 1; i++)
this->next[i] = i + 1;
this->next[this->cap] = -1;
this->firstEmpty = 0;
this->size_elems = 0;
this->rel = r;
}
这是我的添加功能:
void SortedIndexedList::add(TComp e) {
if (this->size() == this->cap)
this->resize();
if (this->size() == 0)
{
int newPosition = this->firstEmpty;
this->elems[newPosition] = e;
this->firstEmpty = this->next[this->firstEmpty];
this->next[newPosition] = this->head;
this->head = newPosition;
}
else
{
int current = this->head;
int currentPosition = 0;
while (current != -1 && currentPosition < this->size() && rel(this->elems[current], e))
{
current = this->next[current];
currentPosition++;
}
if (current != -1)
{
int nextPos = this->firstEmpty;
this->firstEmpty = this->next[firstEmpty];
this->elems[current] = e;
this->next[nextPos] = this->next[current];
this->next[current] = nextPos;
}
}
this->size_elems++;
}
我想确保它有效,我尝试添加 1,然后是 2,然后是 3,并在每一行上打印元素,但不会添加 I 2 和 3(关系为 <=)。有人可以帮我吗?我无法弄清楚我做错了什么。
解决方案
我认为您在初始化next
数组时跳过了索引:
for (int i = 0; i < this->cap - 1; i++)
this->next[i] = i + 1;
this->next[this->cap] = -1;
您将this->cap - 2
在 for 循环 ( i < this->cap - 1
) 中上升,因此this->cap - 1
永远不会被赋予值。
推荐阅读
- winapi - 如何使用自定义数据在外螺纹上安装挂钩程序?
- node.js - 在nodejs中只接收带有对象标签的空数组
- python - 用于翻译的 TensorFlow 数据集 - 如何使用 WMT14 手动下载?
- javascript - 使用 Javascript 将标签 [start] [end] 包裹在 textarea 中的选定文本周围
- prometheus - Unavailable Prometheus service with WAL segment loaded entries in log file
- ipv6 - Formula for Supernetting the multiple blocks of IPv6 pools
- javascript - Image Crop And Compression before upload
- c++ - Initialise char array with string variable in C++?
- c# - DiscordBot:Unable to resolve service for type 'Discord.WebSocket.DiscordSocketClient' while attempting to activate 'LockDocler.Services.CommandHandler
- ssl - traefik ssl certificate generation for cname record "tls: bad certificate"