Reputation: 173
I'm trying to implement my own linked list using vectors and pointers. The problem I'm have is that I can't get the first node to point to the second node.
Here's my code and what I've tried:
struct Node {
Node* previous;
Node* next;
int data;
};
// Initialize: Create Vector size 20 and first node
void LinkedList::init() {
vecList.resize(20, NULL); // Vector of size 20
Node* head = new Node(); // Create head node
head->previous = NULL; // Previous point set to null
head->next = vecList[1]; // Next pointer set to next position
head->data = 0; // Data set at value 0
vecList[0] = head; // Put head node in first position
count = 1; // Increase count by 1
}
// Add Node to array
void LinkedList::push_back(Node* node, int data) {
count += 1;
node = new Node();
node->next = vecList[count + 1];
node->previous = vecList[count - 1];
node->data = data;
vecList[count - 1] = node;
}
The data has been passed in and will displayed using:
cout << linkedlist.vecList[1]->data << endl;
But if I try this way to display I get error saying the next pointer is <Unable to read memory>
cout << linkedlist.vecList[0]->next->data << endl;
Upvotes: 0
Views: 1203
Reputation: 1012
You forgot to set the next
pointer of the previous Node
in the push_back
method.
If count
is a member variable of the list containing the number of entries you have to change the method like this:
EDIT: actually you have to increment count
in the end because array indices start with zero.
void LinkedList::push_back(Node * node, int data){
node = new Node();
node->next = NULL; // NULL because next element does not exist yet
node->previous = vecList[count - 1];
node->data = data;
vecList[count] = node;
vecList[count-1]->next = vecList[count];
count++;
}
Still it's a bit strange that you try to implement a linked list with a vector or array because that actually defeats the advantages of a list...
Upvotes: 2
Reputation: 15232
It looks like vecList
is a vector/array of pointers to Node
.
When you init, you let the first element point to the second element:
void LinkedList::init(){
...
head->next = vecList[1];
But at this point, the second element does not exist yet. So you cannot point to it yet. Something similar is wrong at the push_back
function.
Upvotes: 2