创建一个没有指针但有索引的链表
Creating a linked list without pointers but indices
我的老师希望我创建类似链表的东西,但使用索引而不是指针。所以Node
包含int data
和int index
.
你能给我一个提示,我会怎么做吗?我知道如何使用指针创建它,但是没有它们怎么办?他提到游泳池是一个容器。
你的结构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];
一种可能的方法是使用Nodes
数组,其中每个节点存储一个(数组(索引到prev
和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
}
此外,您可能必须动态分配Node
数组,实现一些簿记来获取和释放数组中的空间:例如,将未占用的索引存储在Node
数组中的bool
数组,以及每次添加或删除新的Node
/索引时都会更新它的两个函数(它将被碎片化,因为节点并不总是连续的(; 查找Node
的索引 在数组中:例如,从数组的第一个地址中减去Node
的地址。
以下是使用上述技术的双向链表的可能接口
:template <typename T> // T type Node in your case
class DList
{
T** head; // array of pointers of type Node
int first; // index of first Node
int last; // index of last Node
bool* available; // array of available indexes
int list_size; // size of list
int get_index(); // search for index with value true in bool available
void return_index(int i); // mark index as free in bool available
std::ptrdiff_t link_index(T*& l) const // get index of Node
void init(); // initialize data members
void create(); // allocate arrays: head and available
void clear(); // delete array elements
void destroy(); // delete head
public:
DList(); // call create() and init()
~DList(); // call clear() and destroy()
void push_back(T* l);
void push_front(T* l);
void insert(T*& ref, T* l); // insert l before ref
T* erase(T* l); // erase current (i.e. l) and return next
T* advance(T* l, int n); // return n-th link before or after currnet
std::size_t size() const;
int capacity () const { return list_size; }
};
您可以将其用作基准并自行实现某些内容。
template <typename T>
void DList<T>::push_back(T* l)
{
if (l == nullptr)
{
throw std::invalid_argument("Dlist::push_back()::Null pointer as argument!n");
}
int index = get_index();
head[index] = l;
if (last != -1)
{
head[last]->next = index;
head[index]->prev = last;
}
else
{
first = index;
head[index]->prev = -1;
}
last = index;
head[index]->next = -1;
}
相关文章:
- C++,指针数组,指向双链表中的条目
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 链表指针问题
- 将链表转换为指针数组时出错
- 如何实现容纳整数和无效指针的双向链表?
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 为什么我在空指针错误(链表)中获取成员访问权限
- 链表删除功能的单指针 // 是可能的
- 如何深度复制链表对象指针
- 链表 - 使用后面的指针在末尾插入
- 链表和指针在C++中的点
- 未分配被释放的指针(将堆栈实现为链表时)
- 使用双指针和递归反转链表
- 使用函数引用指向节点的指针删除链表中的节点?
- 使用 XOR 操作仅使用 2 个指针反转链表
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 指针永远不会在链表深层复制构造函数中达到 null
- 链表指针赋值为什么我们不能直接将尾巴分配给 temp 而不是尾巴>尾巴下一个
- 如何从文件读取到动态分配的指向结构的指针链表中?
- C++指针链表