Skip to content

Instantly share code, notes, and snippets.

@hutorny
Created March 23, 2017 09:41
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 hutorny/cfaf26a381002577287474e76f817d59 to your computer and use it in GitHub Desktop.
Save hutorny/cfaf26a381002577287474e76f817d59 to your computer and use it in GitHub Desktop.
Simple doubly linked list imlementation
/* simple doubly linked list imlementation */
template<typename T>
class list {
public:
inline T* pfront() noexcept { return head ? &head->data : nullptr; }
inline T* pback() noexcept { return tail ? &tail->data : nullptr; }
template<typename ... Args>
inline T* construct(Args ... __args) noexcept {
return &append(new item(__args ...))->data;
}
inline void destruct(T* p) noexcept {
delete remove(reinterpret_cast<item*>(p));
}
template<typename ... Args>
inline void foreach(bool(*f)(T&, Args ... args), Args ... args) noexcept {
item* i = head;
while( i && f(i->data, args ...)) i = i->next;
}
private:
struct item {
template<typename ... Args>
inline item(Args ... args) noexcept : data(args ...) {}
T data;
item* next = nullptr;
item* prev = nullptr;
};
inline item* append(item* i) noexcept {
if( ! tail ) tail = head = i;
else {
tail->next = i;
i->prev = tail;
}
return i;
}
inline item* remove(item* i) noexcept {
if( head == i ) head = i->next;
if( tail == i ) tail = i->prev;
if( i->next ) i->next->prev = i->prev;
if( i->prev ) i->prev->next = i->next;
return i;
}
item* head = nullptr;
item* tail = nullptr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment