c++ - singly linked list simulated with dynamic arrays -


my code suppose create singly linked list using , array of nodes.

each node has variable item hold data , variable next holds index of next node in list. last node has -1 in next data field simulate nullptr. head holds index of first node in list.

for reason when create pointer point node in array it gives following error:

error: cannot convert 'node' '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 should int or size_t, since code using indices instead of pointers. since it's array, can use new 1 time allocation of fixed maximum size, if similar std::array.


Comments