Reputation: 325
I would like to add a node to the front of the list by calling an object and print the length of the list. So far I keep getting a segmentation fault. I want something basic enough that I can build ideas from:
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next; //creating a pointer to store the address of the next node or null (at the end of a linked list)
int key;
Node(int d){
data = d;
next = NULL;
key = -1;
}
};
class LinkedList {
public:
Node *head;
LinkedList (){
head = NULL;
}
void addNodetoFront(int data){
Node *n = new Node(data);//allocate memory on the heap with address that is returned to n (pointer)
n->next=head;
head=n;
if(n != NULL){
n->key = n->next->key+1;
}
else{
n->key = 1;
}
}
};
int main(){
LinkedList linkedlist;
linkedlist.addNodetoFront(2);
linkedlist.addNodetoFront(3);
linkedlist.addNodetoFront(4);
linkedlist.addNodetoFront(5);
linkedlist.addNodetoFront(26);
linkedlist.addNodetoFront(27);
linkedlist.addNodetoFront(9);
linkedlist.addNodetoFront(45);
linkedlist.addNodetoFront(87);
return 0;
}
Expected is linked list of 9 nodes, and the program prints 9 elements.
Upvotes: 2
Views: 183
Reputation: 63481
Your head
starts off as NULL. When you add the first node, then that node becomes the head, and its next
pointer becomes NULL. Now, look at this:
if(n != NULL){
n->key = n->next->key+1; // But n->next is NULL :(
}
Above, n->next->key
is undefined behavior, as you are dereferencing a NULL pointer. Furthermore, while it's actually impossible for n
to be NULL, the following logic for if n
hypothetically could be NULL is crazy:
else{
n->key = 1; // But you said n was NULL :(
}
The only way any of this makes sense is if you actually had a typo in your test and you meant:
if(n->next != NULL)
Putting this all together, makes your function look like this:
void addNodetoFront(int data)
{
Node *n = new Node(data);
n->next = head;
head = n;
if (n->next != NULL) {
n->key = n->next->key + 1;
} else {
n->key = 1;
}
}
Alternatively, the following more compact style achieves exactly the same:
void addNodetoFront(int data)
{
Node *n = new Node(data);
n->next = head;
n->key = (head ? head->key + 1 : 1);
head = n;
}
Upvotes: 2