gpt4 book ai didi

c++ - 索引单链表

转载 作者:行者123 更新时间:2023-11-28 01:46:30 25 4
gpt4 key购买 nike

我想创建一个单向链表。我已经有一个不允许对其进行索引的实现。我想添加此功能,但我不确定该怎么做。

Linked List

所以基本上头部应该有索引“1”。但我自己想不通,我应该在 If 语句中做什么才能使索引每一步增加 1

void AddNode (int addData)
{
nodePtr NewNode = new node;
NewNode->next = NULL;
NewNode->data = addData;

if (head != NULL)
{
curr = head;
while(curr->next != NULL)
{
curr = curr->next;
}
curr->next = NewNode;
NewNode->index;
}
else
{
head = NewNode;
NewNode->index = 1;
}
}

最佳答案

你的意思是能够做一些事情,比如通过 get(index) 获取链表节点?

另外,你的头不应该有索引 1,它应该是 0。这不符合从零开始索引的标准做法。

链表在技术上没有索引,也不应该存储它们。看起来链表可能不是你正在做的事情的正确数据结构,但是你可以用这样的循环来处理它(如果我的 c++ 语法生锈了请原谅)

int get(int index) {
Node current = head;
for (int x = 0; x < index; x++) {
if (current->next == null) {
//some sort of error handling for index out of bounds
} else {
current = current->next;
}
}
return current->data
}

get(2) 将返回列表的第三个元素。

关于c++ - 索引单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44848837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com