Hello, I am writing a single-linked list, here’s a piece:
template<typename T> struct one_list; template<typename T> struct node_list { node_list(const T& val) : data(val), next(nullptr) { } const T& get_data() { return data; } node_list<T>* get_next() { return next; } friend struct one_list<T>; private: T data; node_list<T>* next; }; template<typename T> struct one_list { typedef node_list<T> node_t; one_list() : size(0), root(nullptr) { } void push(const T& val) { ++size; node_t* ptr = &(*(root + (size - 1))); ptr = new node_t(val); ptr->next = nullptr; } void pop() { if (size) { node_t* ptr = root + size - 1; delete ptr; ptr = nullptr; --size; } else throw std::runtime_error("remove nullable element\n"); } const size_t& get_size() { return size; } node_t* get_root() { return root; } private: size_t size; node_t* root; }; int main() { one_list<int> list; list.push(1); list.push(2); list.push(3); list.pop(); } an exception is thrown in the pop method in a line with delete ptr ... I can’t understand why root is still zero ... help solve the problem
pushmethod is also strangely written. It would be necessary first to allocate memory (makenew), and only then assign pointers. You first haveptr=&(*(root + (size - 1)));, that is, some value was assigned, and thenptr=new node- you assign the value again - Alexey Sarovskypushmethod should look something like this:node_t* ptr = new node_t(val); ptr->next=nullptr; (root+size)->next = ptr; ++size;node_t* ptr = new node_t(val); ptr->next=nullptr; (root+size)->next = ptr; ++size;- Alexey Sarovsky