I am trying to program linked lists, this time without looking at the book. The program is throwing an unhandled exception, accessing memory violation... then it references a memory address.
Hopefully my code is not egregious and I'm starting to come around to something workable. I would love to get my head wrapped around linked lists so I can move on to bigger and better things. Any assistance offered is very appreciated.
The first class creates the list nodes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
class ListNode
{
friendclass List;
int data;
ListNode *next;
public:
ListNode();
ListNode(int);
};
ListNode::ListNode()
{ data = 0;
}
ListNode::ListNode(int v): data(v){}
I initialized all ListNode variables like you said.
The debugger seems to be stopping at line 30. I tried to investigate further, but it's over my head, still.
In the list constructor, I was trying to create the head of the list, the starting point. I was thinking no ListNode exists yet.. so I created one and set it to first. Would it be better if I coded it this way:
Unfortunately, I don't understand my addNode function either. The problem is my book doesn't break it down well. It gives me one large program (templated) that spans almost 3 pages and just references it throughout the chapter. It's a little overwhelming.
Here is what I have now! It still doesn't compile, it melts down with the same symptom. Hopefully the addNode() function is at least a little bit deconfusified.
In your List constructor, you are dynamically allocating a node and pointing the node's next pointer to itself. Nothing is being stored in the list, and when the constructor returns, there is a memory leak (nothing points to the allocated node).
Instead, just set the values of first and last to NULL. This indicates that there are no elements in the list to start.
In addNode you need to be careful with a number of things.
1. Check to see whether the list is empty, and manage first and last appropriately.
2. If you are just adding to the end of the list, there is no need to iterate through the whole list (lines 43 and 44). Just start at last.
3. Be careful assigning next pointers. Right now you are pointing the next pointer of the last element to the new element (line 46) and then to itself (line 47), and then re-assigning it to NULL (line 48). Draw a picture of the elements of the list as well as the new element and figure out how and when to set each pointer value. This includes first (when necessary), last, last->next and newNode->next.