Skip to content

Instantly share code, notes, and snippets.

@fponticelli
Created October 14, 2013 14:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fponticelli/6977059 to your computer and use it in GitHub Desktop.
Save fponticelli/6977059 to your computer and use it in GitHub Desktop.
#ifndef _LINKEDLIST_H
#define _LINKEDLIST_H
template <typename T>
class LinkedList {
public:
LinkedList();
~LinkedList();
void add(T value);
void remove(T value);
void iterate(void (*iterator)(T));
protected:
private:
typedef struct node {
T data;
node * next;
} node;
typedef node * link;
link tail;
link head;
};
template <typename T>
LinkedList<T>::LinkedList()
{
head = NULL;
tail = NULL;
}
template <typename T>
LinkedList<T>::~LinkedList () {
while(NULL != tail)
{
link next = tail->next;
remove(tail->data);
tail = next;
}
}
template <typename T>
void LinkedList<T>::remove(T value) {
link prev = NULL;
for(link n = tail; NULL != n; n = n->next) {
if(n->data == value)
{
if(NULL == prev) {
tail = n->next;
} else {
prev->next = n->next;
n->next = NULL;
}
if(head == n)
{
head = prev;
}
delete n;
break;
}
prev = n;
}
}
template <typename T>
void LinkedList<T>::add(T value)
{
link n = new node;
// TODO if (NULL == n)
n->data = value;
n->next = NULL;
if(NULL == head)
{
tail = head = n;
} else {
head->next = n;
head = n;
}
}
template <typename T>
void LinkedList<T>::iterate(void (*iterator)(T))
{
for(link n = tail; NULL != n; n = n->next) {
iterator(n->data);
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment