Я попытался создать свою собственную версию контейнера списка. У меня возникла следующая проблема. Мое приложение скомпилировано, я поместил реализацию в заголовок для класса шаблона, но когда я пытаюсь запустить мое приложение, он падает... Я не знаю, что я сделал неправильно. Здесь код:
#ifndef _CH10EX8_
#define _CH10EX8_
#include <iostream>
#include <cstring>
template<typename T>
class List{
private:
struct Item{
Item* next;
int index;
T data;
};
Item* head;
public:
List();
~List();
void addItem(const T&);
void showList()const;
T& getItem(int)const;
};
template<typename T>
List<T>::List()
{
head = NULL;
};
template<typename T>
List<T>::~List()
{
Item* current = head;
Item* prev;
while(current->next != NULL){
prev = current;
current = current->next;
delete prev;
}
delete current;
delete head;
}
template<typename T>
void List<T>::addItem(const T& val){
static int index = 0;
Item* toAdd = new Item;
toAdd->data = val;
toAdd->index = index;
++index;
if(head == NULL){
toAdd = head;
head->next = NULL;
}
else{
Item* current = head;
while(current->next != NULL)
current = current->next;
current->next = toAdd;
toAdd->next = NULL;
}
}
template<typename T>
void List<T>::showList()const{
Item* current = head;
while(current->next != NULL)
std::cout << "Data: " << current->data
<< "At index: " << current->index << std::endl;
}
template<typename T>
T& List<T>::getItem(int id)const{
Item* current = head;
if(current->index != id){
while(current->next->index != id)
{
if(current->next == NULL){
std::cout << "Item at index " << id << "not found\n";
break;
}
}
return current->data;
}
else
return current->data;
}
#endif
это для заголовка. Здесь моя главная:
#include "ch10ex8.h"
int main(int argc,char** argv){
List<double> m_list;
for(double id = 0; id < 50.0; ++id)
m_list.addItem(id);
m_list.showList();
std::cout << "Found item: " << m_list.getItem(20) << std::endl
<< "At index: " << 20 << std::endl;
return 0;
}
Этот фрагмент кода определенно неисправен:
if(head == NULL){
toAdd = head;
head->next = NULL;
}
Вы не можете сделать head->next = NULL
если head
NULL.