创建一个没有指针但索引的链表

时间:2017-07-01 09:40:32

标签: c++ data-structures linked-list

我的老师要我创建类似链接列表的东西但是使用索引而不是指针。因此Node包含int dataint index

你能告诉我一个怎么办?我知道如何使用指针创建它但如何没有它们?他提到游泳池是一个集装箱。

2 个答案:

答案 0 :(得分:0)

你的结构Node就像这样

struct Node {
    int data;
    int index; // index of the entry in the pool to the next node
}

您可以使用vector或数组来创建池

vector<Node*> pool; // stores the pointer to next nodes

现在访问您可以执行的下一个节点

Node* nextNode = pool[currNode->index];

答案 1 :(得分:0)

一种可能的方法是使用PATCH数组,其中每个节点都存储Nodesprev next的(数组)索引。因此,您的Node看起来像是:

Node

此外,您可能需要动态分配struct Node { T data; int prev; // index of the previous Node of the list int next; // index of the next Node of the list } 数组,对数组中的 get free 空间实施一些记账:例如{ {1}}数组,用于存储Node数组中未占用的索引,以及每次添加或删除新bool /索引时将更新它的两个函数(它将被分段为节点赢得不要总是连续的;在数组中找到Node的索引:例如,从数组的第一个地址中减去Node的地址。

以下是使用上述技术的双向链表的可能界面如何:

Node

您可以将其作为基准并自行实施。

Node