2015-09-26 61 views
0

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

每个节点都有一个变量项,它保存数据和下一个变量,它保存列表中下一个节点的索引。最后一个节点在其下一个数据字段中有-1来模拟nullptr。头部保存列表中第一个节点的索引。

由于某种原因,当我创建一个指针指向它,它提供了以下错误阵列中某一节点:

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; 
} 

回答

1

current应该是int或size_t,因为代码使用索引而不是指针。由于它是一个数组,因此如果要与std :: array类似,则只能使用new来分配一个固定的最大大小。

+0

你的想法给了我正确的方向。你是一个生命保护谢谢 – wazeeer

+1

@wazeeer - 一旦你得到它的工作,你可能想尝试实现一个只改变下一个索引的自顶向下合并排序。它会将索引返回到排序列表的“头部”,然后array [head] .next将包含第二个节点的索引,依此类推,直到array []。next == -1。对于使用本地索引数组的列表,array_of_indices [i]指向带有pow(2,i)节点的列表,它的速度更快,但自上而下的版本是更容易理解。 – rcgldr