【问题标题】:Sorted Indexed List using linked list on array使用数组上的链表排序索引列表
【发布时间】:2020-08-15 06:00:02
【问题描述】:

我有一个项目使用数组上的单链表来实现排序索引列表。 当我尝试执行添加功能时,我遇到了一些问题。 这就是我的构造函数的样子:

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,并在每一行上打印元素,但不会添加我的 2 和 3(关系是

【问题讨论】:

  • 您不必使用this-&gt; 来访问班级成员。
  • 嗨@Gaboru你能解决这个问题吗?
  • 嗨!还是无法解决

标签: c++ list sorting data-structures


【解决方案1】:

我认为您在初始化 next 数组时跳过了索引:

for (int i = 0; i < this->cap - 1; i++)
        this->next[i] = i + 1;
this->next[this->cap] = -1;

您将在 for 循环 (i &lt; this-&gt;cap - 1) 中上升到 this-&gt;cap - 2,因此永远不会给 this-&gt;cap - 1 赋值。

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2010-10-31
    • 2014-02-04
    • 1970-01-01
    相关资源
    最近更新 更多