Search code examples
c++pointerslinked-listdynamic-memory-allocation

singly linked list simulated with dynamic arrays


my code is suppose to create a singly linked list using and array of nodes.

each Node has variable item which hold data and variable next which holds the index of the next node in the list. the last node has -1 in its next data field to simulate a nullptr. head holds the index of the first node in the list.

for some reason when i create a pointer to point to a certain node in the array it it gives the following error:

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

Solution

  • current should be an int or a size_t, since the code is using indices instead of pointers. Since it's an array, you can only use new for a one time allocation of a fixed maximum size, if this is to be similar to std::array.