Created
October 14, 2013 14:59
-
-
Save fponticelli/6977059 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 _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