In C++ you do it this way (assuming you want your own implementation
instead of the STL one):
#include <iostream>
using namespace std;
template <class T>
class List {
protected:
struct Node {
Node* next;
T val;
// Constructor
Node() : next(0) {}
Node(Node *p_next) : next(p_next) {}
Node(Node *p_next, const T& p_val) : next(p_next), val(p_val) {}
};
Node* head;
static Node c_end;
public:
struct iterator {
Node* node;
iterator(Node *p_node) : node(p_node) {
}
bool operator!=(const iterator& another) {
return node != another.node;
}
void operator++() {
node = node->next;
}
T operator*() {
return node->val;
}
};
List() {
head = &c_end;
}
iterator begin() {
return iterator(head);
}
iterator end() {
return iterator(&c_end);
}
void push_front(const T& p_val) {
head = new Node(head, p_val);
}
void insert_after(iterator p_where, const T& p_val) {
p_where.node->next = new Node(p_where.node->next, p_val);
}
};
template <typename T> typename List<T>::Node List<T>::c_end;
int main()
{
List<int> myList;
myList.push_front(9);
myList.push_front(5);
myList.push_front(4);
myList.push_front(1);
myList.push_front(3);
List<int>::iterator it = myList.begin();
++it;
++it;
myList.insert_after(it, 1);
for (List<int>::iterator i = myList.begin(); i != myList.end(); ++i) {
cout << *i << ", ";
}
cout << endl;
return 0;
}
// Output: 3, 1, 4, 1, 5, 9,
Of course you can improve it a lot, adding a pointer to the tail node,
push_back's, pointer to previous element (double linked list), etc...
and as a homework, implement a destructor so that delete is called on
every element (otherwise it is leaking memory)
Regards,
Edson