Skip to content

Instantly share code, notes, and snippets.

@profan
Last active February 15, 2016 05:29
Show Gist options
  • Save profan/709545169126e2dbbdb0 to your computer and use it in GitHub Desktop.
Save profan/709545169126e2dbbdb0 to your computer and use it in GitHub Desktop.
Intrusive single linked list, wouldn't recommend anyone actually use it :D
/**
* Intrusive single linked list, uses next pointer already present in the type
* to avoid extra dynamic memory allocation.
*/
struct ILinkedList(T) {
T* head_;
void add(T* item) {
this.add(&head_, item);
} //add
private void add(T** node, T* new_node) {
new_node.next = *node;
*node = new_node;
} //add
void opOpAssign(string op: "~")(T* item) {
this.add(&head_, item);
} //opOpAssign
int opApply(scope int delegate(T*) dg) {
int result = 0;
for (auto cur = head_; cur != null; cur = cur.next) {
result = dg(cur);
if (result) break;
}
return result;
} //opApply
/**
* Unlinks the head of the linked list, making the next element
* the new head of the list. (1, 2, 3, 4) -> (2, 3, 4)
*/
void poll() {
if (head_) {
head_ = head_.next;
}
} //poll
T* head() {
return head_;
} //head
void clear() {
head_ = null;
} //clear
@property bool empty() {
return head_ == null;
} //empty
} //ILinkedList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment