Skip to content

Instantly share code, notes, and snippets.

@alphaKAI
Created July 23, 2016 12:03
Show Gist options
  • Select an option

  • Save alphaKAI/1c557cfa154724aaddd57636397c484b to your computer and use it in GitHub Desktop.

Select an option

Save alphaKAI/1c557cfa154724aaddd57636397c484b to your computer and use it in GitHub Desktop.
Minimal Stack&Queue data structure Implementation in D
/*
Minimal Queue data structure Implementation in D
Copyright (c) 2016 alphaKAI
This software is released under the MIT License.
*/
import core.memory;
struct Node(T) {
Node!T* next;
T value;
}
struct List(T) {
Node!T* head = null;
Node!T* tail = null;
void push(Node!T* node) {
if (head is null) {
head = node;
tail = node;
} else {
auto tp = head;
head = node;
tp.next = head;
}
}
Node!T* pop() {
if (tail is null) {
return null;
} else {
if (tail.next is null) {
auto tp = tail;
tail = null;
head = null;
return tp;
} else {
auto tp = tail;
tail = tp.next;
return tp;
}
}
}
@property bool empty() {
return tail is null;
}
}
struct Queue(T) {
List!T list;
void push(T val) {
Node!T* node = cast(Node!T*)GC.malloc(Node!T.sizeof, GC.BlkAttr.NO_SCAN);
node.value = val;
node.next = null;
list.push(node);
}
T pop() {
Node!T* rt = list.pop;
if (rt is null) throw new Error("tail is null");
T rv = rt.value;
GC.free(rt);
return rv;
}
}
/*
Minimal Stack data structure Implementation in D
Copyright (c) 2016 alphaKAI
This software is released under the MIT License.
*/
import core.memory;
struct Node(T) {
Node!T* next;
T value;
}
struct List(T) {
Node!T* head = null;
void push(Node!T* node) {
if (head is null) {
head = node;
} else {
auto tp = head;
head = node;
head.next = tp;
}
}
Node!T* pop() {
if (head is null) {
return null;
} else {
if (head.next is null) {
auto tp = head;
head = null;
return tp;
} else {
auto tp = head;
head = tp.next;
return tp;
}
}
}
@property bool empty() {
return head is null;
}
}
struct Stack(T) {
List!T list;
void push(T val) {
Node!T* node = cast(Node!T*)GC.malloc(Node!T.sizeof, GC.BlkAttr.NO_SCAN);
node.value = val;
node.next = null;
list.push(node);
}
T pop() {
Node!T* rt = list.pop;
if (rt is null) throw new Error("head is null");
T rv = rt.value;
GC.free(rt);
return rv;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment