【发布时间】:2023-03-29 03:48:02
【问题描述】:
我的代码假设使用节点数组创建一个单链表。
每个节点都有变量 item 保存数据和变量 next 保存列表中下一个节点的索引。最后一个节点在其下一个数据字段中具有 -1 以模拟 nullptr。 head 保存列表中第一个节点的索引。
由于某种原因,当我创建一个指向数组中某个节点的指针时,它会给出以下错误:
错误:初始化时无法将“Node”转换为“Node*”|
#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;
}
【问题讨论】:
标签: c++ pointers linked-list dynamic-memory-allocation