The code below is a node class, for implementation of linked list class. However, when running the code, there's error "EXC_BAD_ACCESS" in the member function Node<T>::Next(). Can anyone help me?
template<typename T>
void LinkedList<T>::InsertNode(T node_data)
{
////////////////////////////////////////////////
// we can't do this. nd has automatic storage duration
// the node will be destroyed when we return from the function
//
// create a ListNode
// Node<T> nd(node_data);
////////////////////////////////////////////////
Node<T>* tmp = new Node<T>(node_data); // create a node with dynamic storage duration
// *** note: you would need to define the other foundation operations (destructor etc.)
if (head == NULL)
{
// head->Next(tmp); // ******
head = tmp; // *** if head was null, this node becomes the head
return;
}
// insert ListNode, if the Linked List is empty, return
Node<T>* last = head;
while (last->Next() != NULL)
{
last = last->Next();
}
last->Next(tmp);
return;
}
I got it! The Node object created in the InsertNode function will last until the end of the function. However, the Node pointer which I assign to the next member of the last node, is still there. So the pointer points to the beginning of the stack.
Thank you! I think it will works now.