Created
May 14, 2011 18:20
-
-
Save erenon/972481 to your computer and use it in GitHub Desktop.
Custom simple list implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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