I am writing a program that implements doubly linked lists and am required to add to the front, back, and in between any node in the list. I receive an error stating that I have an invalid null pointer and am confused on where I have made this error for each function.
The tough part here is that any time you add a node, you have to worry about adjusting all the affected prev and next pointers, and the head and tail pointers too. I suggest that you add a private method:
1 2 3 4 5 6
// Add newNode after link, which is either head or some item's next pointer
void
GroceryList::addAfter(ItemType *&link, ItemType *newNode)
{
...
}
Notice here that link is a reference to a next pointer or to head. That way, when change link, you'll be changing the actual link. With this method (and a constructor in ItemType), the rest of it gets easy. For example:
Quite possibly. In your version, line 3 changes link to point to newNode. Then line 4 changes newNode->prev to link, which is now newNode. The effect is the same as newNode->prev = newNode.
Link might point to an existing node. So as a first cut you want to do this:
newNode->next = link;
link = newNode;
Now:
- what should newNode->prev point to?
- Some node's prev pointer might have to change to point to newNode
- What if newNode is the new tail of the list. You'll have to adjust tail.
- What if newNode is the first item in the list (note that in this case link is head).