Firstly, this is my first posting here. I've read through the guidelines, and have hopefully managed to follow them. If not, please advise! :)
Problem: I have written a class for a singly linked list, which uses a separate Node class. When my test program accesses a function that iterates through the linked list (Search function, Print list function); if the function goes to the end of the list, the program segfaults. I'm assuming that there is an issue with the last Node not correctly pointing to NULL, and I suspect that I may be dereferencing the null ptr somehow, but I cannot locate the error. I've included what I *think* are the relevant bits; if more is needed, please let me know!
Node header:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class Node
{
public:
Node(const int& newdata = 0, Node* newlink = NULL); //constructor
void setdata(const int newdata){data = newdata;} //Sets data
void setlink(Node* newlink) {link = newlink;} //Set link
int getdata() {return data;}
Node* getlink() {return link;}
private:
int data;
Node* link;
};
void insert(Node*& headptr, const int entry);
|
Node implementation:
1 2 3 4 5 6 7 8 9 10 11
|
Node::Node(const int& newdata, Node* newlink)
{
data = newdata;
link = NULL;
}
void insert(Node*& headptr, const int entry)
{
headptr = new Node(entry);
}
|
Linked list constructor:
1 2 3 4 5 6 7
|
List::List()
{
used = 0;
Node* headptr;
headptr = NULL;
// cout << "headptr link: " << headptr->getlink() << endl;
}
|
Insert function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
void List::inserthead(const int& entry)
{
if (headptr == NULL)
{
insert(headptr, entry);
}
else
{
Node* tempptr = new Node();
tempptr->setlink(headptr);
tempptr->setdata(entry);
headptr = tempptr;
}
used++;
cout << "headptr link: " << headptr->getlink() << endl;
return;
}
|
Print function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void List::printList()
{
assert (headptr != NULL);
Node* tempptr;
tempptr = headptr;
int counter = 1;
while (tempptr != NULL)
{
cout << "Node " << counter << ": " << tempptr->getdata() << endl;
tempptr = tempptr->getlink();
counter++;
}
return;
}
|
Expected output (Nodes created holding 11, 22, 33, 44, 55 in that order)
Node 1: 55
Node 2: 44
Node 3: 33
Node 4: 22
Node 5: 11
Actual output:
Node 1: 55
Node 2: 44
Node 3: 33
Node 4: 22
Node 5: 11
Node 6: 1267779745
*segmentation fault here*
Sorry for the long post, and any help is appreciated!