c++ - 索引单链表

标签 c++

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

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/

相关文章:

c++ - 用 boost::geometry 扩展多边形?

c++ - 为什么 std::map 没有 insert(key &, value & v) 类型的插入函数

c++ - 从外部文件获取输入?

c++ - 字段访问 - C++ 中的多态和非多态类型

c++ - 将指针数组传递给函数时遇到问题

C++17 Using Class Template Argument Deduction 关于保存函数返回值的类型的指南

c++ - 确保在对象更改时重新排序 multiset

c++ - 使用 cin>>"(variable created)";作为暂停选项

c++ - 在 OpenCV 中将 float 转换为 unsigned char

c++ - 出现错误: “nvlink error : Undefined reference to ' _ZN8Strategy8backtestEPddd'”