I was trying to implement the linked list stl but I always get runtime error if someone can help me solve this problem please. What I was doing is when inserting an element I check if it's the first element if it is I make the head and tail point to it if not I use the node's next pointer to point to the new element and move the tail so it point to the last inserted element the error appears in the insert function.
#include <iostream>
using namespace std;
template<typename T>
struct Node {
T item;
Node *next = nullptr;
};
template<typename T>
class list {
static int sz;
Node<T> *head, *tail;
public:
void insert(T x) {
Node<T> new_node;
new_node.item = x;
if (!sz) {
*head = new_node;
*tail = new_node;
} else {
tail->next = &new_node;
*tail = new_node;
}
sz++;
}
int size() {
return sz;
}
friend ostream &operator<<(ostream &os, list<T> &o) {
while (o.head->next != nullptr) {
os << o.head->item << " ";
o.head = o.head->next;
}
return os;
}
};
template<typename T>
int list<T>::sz = 0;
int main() {
list<int> l;
l.insert(5);
l.insert(6);
l.insert(7);
cout << l.size() << endl;
cout << l << endl;
return 0;
}