Reputation: 3
I can't get this program to attach the node to the end of the linked list. I know it has to do something with the "addBack" function because the "addFront" function works perfectly. I think this should be sufficient, but if more code is required, merely ask and ye shall receive.
template <typename E>
void SLinkedList<E>::addBack(const E& e)
{
E *temp = head;
while (temp -> next != NULL)
temp = temp -> next;
SNode<E> * v = new SNode<E>;
temp -> next = v;
v -> elem = e;
v -> next = NULL;
}
Upvotes: 0
Views: 674
Reputation: 336
You had two problems with this code. First the head is not a pointer of type E , instead it is pointer of type SNode. 2ndly list may be empty when first item is being added (head will be NULL). So you need to handle that case separately. Following code should work:
template <typename E>
void SLinkedList<E>::addBack(const E& e)
{
SNode<E> * v = new SNode<E>;
v -> elem = e;
v -> next = NULL;
if(head == NULL) //list is empty
head = v;
else
{
SNode<E> *temp = head;
while (temp -> next != NULL)
temp = temp -> next;
temp -> next = v;
}
}
However for faster insertions, you must have two pointers, both for head and tail of the list. You will not need to iterate the whole list to find the tail. However then you will have to cater for both head and tail when adding and removing a node from list. This will be the function if you have both pointers:
template <typename E>
void SLinkedList<E>::addBack(const E& e)
{
SNode<E> * v = new SNode<E>;
v -> elem = e;
v -> next = NULL;
if(head == NULL) //list is empty
head = tail = v;
else
tail -> next = v;
}
Upvotes: 1