Skip to content

Instantly share code, notes, and snippets.

@hutorny hutorny/list.hpp
Created Mar 23, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.