template <typename T>
class LinkedNode
{
public:
T data;
LinkedNode<T> *next;
LinkedNode<T> *prev;
LinkedNode<T>();
LinkedNode<T>(T);
};
// Default constructor
template <typename T>
LinkedNode<T>::LinkedNode()
{
next = NULL;
prev = NULL;
}
template <typename T>
class LinkedList
{
private:
LinkedNode<T> *head;
public:
LinkedList<T>();
~LinkedList<T>();
void addFront(T);
void addBack(T);
void addAt(T, int);
void removeFront();
void removeBack();
void removeAt(int);
void printList();
};
// Constructor
template <typename T>
LinkedList<T>::LinkedList()
{
head = NULL;
}
// Add new node to front
template <typename T>
void LinkedList<T>::addFront(T d)
{
LinkedNode<T> temp;
temp.data = d;
if (head == NULL)
{
head = &temp;
}
else
{
temp.next = head;
head->prev = &temp;
head = &temp;
}
}
// Add new node to back
template <typename T>
void LinkedList<T>::addBack(T d)
{
// Find the back of this list
LinkedNode<T> *ptr;
ptr = head;
while (ptr->next != NULL) // <------- DIES HERE, MEMORY ACCESS VIOLATION
{
ptr = ptr->next;
}
// Make a new node and join it to the back
LinkedNode<T> temp;
temp.data = d;
temp.prev = ptr;
ptr->next = &temp;
}
Here is a snippet from my linked list system. The issue is that it throws an error on the indicated line. The debugger says that the "head" pointer is pointing to a legitimate memory address of a LinkedNode with no "next" or "prev", but the "ptr" pointer points to address 0xcccccc, not the address of head? I'm really confused, I thought I understood pointers!