Linked List Run Time Error
My console window just come up and said an error has occured and must close, can you figure what's wrong with my code? I've searched the forums and read some of the other people's linked list questions in the forum but no answer. Here's the code and the main function.
Code:
template<typename T>
class List {
public:
List() {
m_head = 0;
m_tail = m_head;
m_size = 0;
}
~List() {
ListNode* save = m_head;
while(save) {
save = save->m_next;
delete m_head;
m_head = save;
}
m_tail = 0;
m_size = 0;
}
void add(const T& elem) {
if(m_head) {
ListNode *link = m_tail;
m_tail->m_next = new ListNode;
m_tail = m_tail->m_next;
m_tail->m_prev = link;
m_tail->m_next = 0;
m_tail->m_data = elem;
} else {
m_tail = new ListNode;
m_tail->m_prev = 0;
m_tail->m_next = 0;
m_tail->m_data = elem;
}
++m_size;
return;
}
void insert(const T& elem, unsigned pos) {
ListNode *targ = locate(pos);
if(targ) {
if(targ == m_head) {
ListNode *link = m_head;
m_head->m_prev = new ListNode;
m_head = m_head->m_prev;
m_head->m_prev = 0;
m_head->m_next = link;
m_head->m_data = elem;
} else {
ListNode *node = new ListNode;
ListNode *link = targ->m_prev;
link->m_next = node;
targ->m_prev = node;
node->m_prev = link;
node->m_next = targ;
node->m_data = elem;
}
++m_size;
}
return;
}
// not done!
void remove(unsigned pos) {
ListNode *targ = locate(pos);
return;
}
void print() const {
ListNode *print = m_head;
while(print) {
std::cout << '[' << print->m_data << ']';
print = print->m_next;
}
return;
}
private:
struct ListNode {
ListNode *m_prev;
ListNode *m_next;
T m_data;
} *m_head, *m_tail;
unsigned m_size;
ListNode *locate(unsigned n) {
if(n > 0 && n <= m_size) {
ListNode *find = 0;
if(n > m_size/2) {
find = m_tail;
while(n < m_size) {
find = find->m_prev;
++n;
}
} else {
find = m_head;
unsigned one(1);
while(n > one) {
find = find->m_next;
--n;
}
}
return find;
} else {
return 0;
}
}
};
This is main.
Code:
int main() {
List<int> list;
list.add(1);
list.add(3);
list.add(4);
list.add(5);
list.insert(2, 2);
list.print();
std::cin.get();
return 0;
}