I am doing a project for school that involves implementing a linked list class. I believe I have all of my functions correct except for my push_back and pop_back. My push_back needs to take a Node* as a parameter and add the node pointed to by the pointer to the end of the list. My pop_back function needs to remove the last node from the list, and return a pointer to this node. Do not delete the node in this function. Simply unlink it from the list. Any help would be great. Here is my class:
I'll help with your push_front() and pop_front() functions so the push_back and pop_back functions will work once they're written. The front functions are missing a detail.
Your push_front function need to assign last a value when the 1st Node is pushed onto an empty list.
That one Node is both 1st and last in the list:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// OK - almostvoid List::push_front(Node* item)
{
if (first == NULL)
{
first = item;
last = first;// Assign last when 1st node pushed
numNodes++;// should = 1. ++ should work though
}
elseif(first != NULL)
{
item->setNextNode(first);
first = item;
numNodes++;
}
}
When you pop the last Node, last must not be left pointing to it:
Node* List::pop_front()
{
Node* tempPtr = first;
if (first == NULL)
{
return NULL;
}
elseif (first != NULL)
{
first = first->getNextNode();// this line makes first = NULL if the last Node was popped.
numNodes--;
if( first == NULL ) last = NULL;// handle case of last Node popped.
}
return tempPtr;
}
Your back functions, even properly coded, would not have worked.
Similar considerations apply to push_back (if 1st node pushed this way then first = last must be assigned) and pop_back where first = NULL must be assigned when the last Node is popped off the back. Hope that gives you something to work on.