add stack functions
This commit is contained in:
parent
73e8322f85
commit
0120100cc7
56
util.d
56
util.d
@ -196,6 +196,37 @@ DLLPush(T, U)(T* list, U* node, U* nil)
|
||||
}
|
||||
}
|
||||
|
||||
struct Stack(T)
|
||||
{
|
||||
Node!(T)* first;
|
||||
}
|
||||
|
||||
void
|
||||
SPush(T, U)(T* stack, U* node, U* nil)
|
||||
{
|
||||
if (CheckNil(nil, stack.first))
|
||||
{
|
||||
stack.first = node;
|
||||
node.next = nil;
|
||||
}
|
||||
else
|
||||
{
|
||||
node.next = stack.first;
|
||||
stack.first = node;
|
||||
}
|
||||
}
|
||||
|
||||
U*
|
||||
SPop(T, U)(T* stack, U* nil)
|
||||
{
|
||||
U* node = stack.first;
|
||||
if (!CheckNil(nil, stack.first))
|
||||
{
|
||||
stack.first = stack.first.next;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
struct Node(T)
|
||||
{
|
||||
Node!(T)* next;
|
||||
@ -934,4 +965,29 @@ unittest
|
||||
|
||||
table[100] = 100;
|
||||
}
|
||||
|
||||
{ // Stack
|
||||
Stack!(u32) stack;
|
||||
Node!(u32) n1 = { value: 1 };
|
||||
Node!(u32) n2 = { value: 2 };
|
||||
Node!(u32) n3 = { value: 3 };
|
||||
|
||||
SPush(&stack, &n1, null);
|
||||
SPush(&stack, &n2, null);
|
||||
SPush(&stack, &n3, null);
|
||||
|
||||
u32 count = 3;
|
||||
for (auto n = stack.first; !CheckNil(null, n); n = n.next, count -= 1)
|
||||
{
|
||||
assert(n.value == count);
|
||||
}
|
||||
|
||||
count = 3;
|
||||
for (auto n = SPop(&stack, cast(Node!(u32)*)null); !CheckNil(null, n); n = SPop(&stack, cast(Node!(u32)*)null), count -= 1)
|
||||
{
|
||||
assert(n.value == count);
|
||||
}
|
||||
|
||||
assert(stack.first == null);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user