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
|
template<typename T>
class list
{
private:
struct Node
{
T data;
Node* next;
Node(const T& data, Node* next = nullptr) : data(data), next(next) {}
};
Node* head = nullptr;
public:
list() = default;
~list();
void insert(int pos, const T& data);
void print() const;
};
#include <iostream>
// Insert data before position pos.
// A negative position is equivalent to 0.
// Positions past the end place data at end.
template<typename T>
void list<T>::insert(int pos, const T& data)
{
Node *nd = head, *prev = nullptr;
for (int i = 0; i < pos && nd; ++i)
{
prev = nd;
nd = nd->next;
}
if (prev)
prev->next = new Node(data, prev->next);
else
head = new Node(data, head);
}
template<typename T>
void list<T>::print() const
{
for (Node* nd = head; nd; nd = nd->next)
std::cout << nd->data << ' ';
std::cout << '\n';
}
template<typename T>
list<T>::~list()
{
for (Node* nd = head; nd; )
{
Node* del = nd;
nd = nd->next;
delete del;
}
}
int main()
{
list<int> a;
a.insert(0, 1);
a.insert(1, 3);
a.insert(2, 5);
a.insert(99, 7); // if position is past the end it's put at the end
a.insert(-99, 0); // negative position equivalent to position 0
a.insert(0, -1);
a.insert(3, 2);
a.insert(5, 4);
a.insert(7, 6);
a.print();
}
|