Hi everyone,
I have the following simple implementation of a Single-Linked List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
|
#include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
#include <memory>
template <typename T>
struct Link
{
T val;
Link *next;
Link(const T &vval = T{}, Link *p = nullptr) : val{vval}, next{p} {}
};
template <typename T>
class List
{
private:
Link<T> *first;
public:
class Iterator;
Iterator begin() { return Iterator(first); }
Iterator end() { return Iterator(nullptr); }
List() : first{nullptr} {}
~List(){ delete first;}
int size() const;
void push_front(const T& val);
void push_back(const T &val);
Iterator insert(Iterator p, const T &v);
};
template <typename T>
void List<T>::push_front(const T& val){
first = new Link<T>(val,first);
}
template <typename T>
typename List<T>::Iterator List<T>::insert(Iterator p, const T &v)
{
Link<T> *tmp = p.current->next;
Link<T> *new_elem = new Link<T>(v, tmp);
p.current->next = new_elem;
return Iterator(new_elem);
}
template <class T>
void List<T>::push_back(const T &v)
{
Iterator p1 = begin();
while (true)
{
Iterator p2 = p1;
++p2;
if (!p2.current)
{
this->insert(p1, v);
return;
}
++p1;
}
}
template <typename T>
class List<T>::Iterator
{
friend class List<T>;
Link<T> *current;
public:
Iterator(Link<T> *p) : current{p} {}
Iterator &operator++()
{
current = current->next;
return *this;
}
T &operator*() { return current->val; }
bool operator==(const Iterator &b) { return current == b.current; }
bool operator!=(const Iterator &b) { return !(*this == b); }
};
int main()
{
List<int> l{};
l.push_front(10);
l.push_front(20);
l.push_back(19);
l.push_back(29);
for (auto& x:l)
{
std::cout << x <<'\n';
}
return 0;
}
|
I am already able to do a Linked-List with smart pointers, which means in this particular case that I can use
std::unique_ptr
. However, I wanted to try with raw ones for learning purposes.
So far, I am having a memory leak, and it's coming from line
47 in the
insert
function.
How can I fix it? I was thinking to just plug a destructor
~Link(){delete next;}
in the Link struct, so when a
Link
goes out of scope in a function, then its is automatically destroyed, but I don't know if this is the right choice. (Notice that I also deleted
first
, my head, in
~List
)
I'd like to understand how I can fix this. Even other workarounds are much appreciated.
Best