Skip to content

Instantly share code, notes, and snippets.

@erenon
Created May 14, 2011 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erenon/972481 to your computer and use it in GitHub Desktop.
Save erenon/972481 to your computer and use it in GitHub Desktop.
Custom simple list implementation
#ifndef LIST_H_
#define LIST_H_
#include <cstddef>
template <typename T>
class List {
struct item {
T value;
item* next;
};
item *head;
item *last;
int value_count;
public:
class iterator {
item *current;
public:
iterator& operator=(item* addr) {
this->current = addr;
return *this;
}
bool operator!=(item* addr) const {
return (current != addr);
}
void operator++() {
current = current->next;
}
void operator++(int dummy) {
current = current->next;
}
T operator*() const {
return current->value;
}
};
List() :value_count(0) {
head = new item;
head->next = NULL;
last = head;
}
item* begin() {
return head->next;
}
item* end() {
return NULL;
}
int size() {
return value_count;
}
void push_back(T value) {
value_count++;
item *new_item = new item;
new_item->value = value;
new_item->next = NULL;
last->next = new_item;
last = new_item;
}
void clear() {
item *first = begin();
item *next;
while (first) {
next = first->next;
delete first;
first = next;
}
head->next = NULL;
last = head;
value_count = 0;
}
~List() {
clear();
delete head;
}
};
#endif /* LIST_H_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment