Having a little trouble setting my head pointer to NULL so that I can check to see if an addition to the linked list is the first one. Here is what I have so far: (this is for a class project btw)
dictionary.h (I am NOT allowed to modify this file)
{
string info;
LinkedListNode *first, *next;
LinkedListNode();
{
next = NULL;
first = NULL; <-- does NOT set first to NULL
}
}
void Dictionary::add (std::string word) <-- Recieves "ape" as the first word
{
string x;
cout << first << endl;
if (first == NULL) <-- first is never NULL so the first node is empty
{
first = new LinkedListNode;
first->data = word;
}
else
{
LinkedListNode *current = first;
LinkedListNode *prev = NULL;
x=current->data; <-- Program crashes here because there is nothing in
the linked list to retrieve data from.
cout << x << endl;
Each LinkedListNode has 2 objects:
1) next : pointer to next node in list
2) data : the value that node holds
________________________________
Something like :
1 2 3 4
Dictionary::Dictionary()
{
first = NULL
}
is all that in necessary when creating a new (empty) Slist.
______________________________________
Also when you add a node, remember to have that nodes pointer point to the next node
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void Dictionary::add (std::string word)
{
if (first == NULL) //EMPTY LIST
{
first = new LinkedListNode; //creates first node in list
first->data = word; //sets first node = word
first->next = NULL; //first node points to NULL
}
else
{
LinkedListNode * temp = first; //temp node = first node
first = new LinkedListNode; //create a new node to go infront
first->data = word; //set first node = word
first->next = temp; //pointing to the next node(temp)
}
}
There are too many problems with your code. The constructor should only initialize member variables. "first" is the only member variable in class Dictionay. Initialize it to NULL in constructor. For info, first and next, you basicaly declared some local variables in your constructor and never used them.
Dictionary::Dictionary () <--- Constructor
{
string info;
LinkedListNode *first, *next; Redefinition of "first"
LinkedListNode(); The semicolon ends the statement, the following block has nothing to do with node's member variables. If you want to initialize node, you have to define a separate constructor for the node.
{
next = NULL;
first = NULL; <-- does NOT set first to NULL
}
was the piece I did not understand about the constructor. Once that was implemented I was able to modify the rest of the code to work as intended.
And I agree 100% with you gd18, there were TOO many problems with that code, but once I got the constructor to work correctly I was able to sort though all the problems and get it to work.