用动态数组模拟的单链表

singly linked list simulated with dynamic arrays

我的代码假设使用节点数组创建一个单链表。

每个节点都有变量 item 保存数据和变量 next 保存列表中下一个节点的索引。最后一个节点在其下一个数据字段中具有 -1 以模拟 nullptr。 head 保存列表中第一个节点的索引。

出于某种原因,当我创建一个指向数组中某个节点的指针时,它给出了以下错误:

error: cannot convert 'Node' to 'Node*' in initialization|

 #include "ArrayList.h"
 #include <iostream>
 using namespace std;

ArrayList::ArrayList(char ch){
    array = new Node[Size];
    (array[0]).item = ch;
    (array[0]).next = 1;

    free = 1;
    head = 0;
  }

int ArrayList::length() const{
    if (head == -1) return 0;
    int counter =0;
    Node* current = array[head]; // problem occurs here

while(current->next != -1 ){
    counter++;
    int index = current->next;
    current  = current[index];
}
    counter++;
    return counter;
}

////////////////////

#ifndef ARRAYLIST_H
#define ARRAYLIST_H
#include <iostream>
using namespace std;



class Node{
public:
    char item;
     int next;

    Node(){
        next = -1;
    }
    Node(char input){
        this->item = input;
        next = -1;
    }
};

class ArrayList{
public:

    ArrayList();
    ArrayList(char ch);

    Node& operator[](int index);

    int length() const;
    char getFirst() const;
    void print() const;
private:
    Node* array;
    int  Size = 5;
    int head = -1;
    int free = 0;
};
#endif

///////////////////////

#include <iostream>
#include "ArrayList.h"
using namespace std;

int main(){
    ArrayList list('1');
    list.print();
    return 0;
}

current 应该是 int 或 size_t,因为代码使用索引而不是指针。由于它是一个数组,如果这类似于 std::array.

,则只能将 new 用于固定最大大小的一次性分配