update stack (again)
This commit is contained in:
parent
3046baee78
commit
c7f77523c4
64
util.d
64
util.d
@ -199,15 +199,30 @@ DLLPush(T, U)(T* list, U* node, U* nil)
|
||||
struct Stack(T)
|
||||
{
|
||||
Node!(T)* top;
|
||||
Node!(T)* free;
|
||||
Node!(T)* nil;
|
||||
}
|
||||
|
||||
void
|
||||
SPush(T)(Stack!(T)* stack, Node!(T)* node, Node!(T)* nil)
|
||||
SPush(T)(Arena* arena, Stack!(T)* stack, T value)
|
||||
{
|
||||
if (CheckNil(nil, stack.top))
|
||||
Node!(T)* node;
|
||||
if (!CheckNil(stack.nil, stack.free))
|
||||
{
|
||||
node = stack.free;
|
||||
stack.free = node.next;
|
||||
}
|
||||
else
|
||||
{
|
||||
node = Alloc!(Node!(T))(arena);
|
||||
}
|
||||
|
||||
node.value = value;
|
||||
|
||||
if (CheckNil(stack.nil, stack.top))
|
||||
{
|
||||
stack.top = node;
|
||||
node.next = nil;
|
||||
node.next = stack.nil;
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -216,15 +231,22 @@ SPush(T)(Stack!(T)* stack, Node!(T)* node, Node!(T)* nil)
|
||||
}
|
||||
}
|
||||
|
||||
Node!(T)*
|
||||
SPop(T)(Stack!(T)* stack, Node!(T)* nil)
|
||||
T
|
||||
SPop(T)(Stack!(T)* stack)
|
||||
{
|
||||
Node!(T)* node = stack.top;
|
||||
if (!CheckNil(nil, stack.top))
|
||||
T result;
|
||||
|
||||
if (!CheckNil(stack.nil, stack.top))
|
||||
{
|
||||
stack.top = stack.top.next;
|
||||
result = stack.top.value;
|
||||
|
||||
Node!(T)* free_node = stack.top;
|
||||
stack.top = free_node.next;
|
||||
free_node.next = stack.free;
|
||||
stack.free = free_node;
|
||||
}
|
||||
return node;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
struct Node(T)
|
||||
@ -967,13 +989,19 @@ unittest
|
||||
|
||||
{ // Stack
|
||||
Stack!(u32) stack;
|
||||
Node!(u32) n1 = { value: 1 };
|
||||
Node!(u32) n2 = { value: 2 };
|
||||
Node!(u32) n3 = { value: 3 };
|
||||
Arena arena = CreateArena(MB(1));
|
||||
|
||||
SPush(&stack, &n1, null);
|
||||
SPush(&stack, &n2, null);
|
||||
SPush(&stack, &n3, null);
|
||||
u32 v1 = 1;
|
||||
u32 v2 = 2;
|
||||
u32 v3 = 3;
|
||||
|
||||
Node!(u32) nil;
|
||||
|
||||
stack.nil = &nil;
|
||||
|
||||
SPush(&arena, &stack, v1);
|
||||
SPush(&arena, &stack, v2);
|
||||
SPush(&arena, &stack, v3);
|
||||
|
||||
u32 count = 3;
|
||||
for (auto n = stack.top; !CheckNil(null, n); n = n.next, count -= 1)
|
||||
@ -982,11 +1010,11 @@ unittest
|
||||
}
|
||||
|
||||
count = 3;
|
||||
for (auto n = SPop(&stack, cast(Node!(u32)*)null); !CheckNil(null, n); n = SPop(&stack, cast(Node!(u32)*)null), count -= 1)
|
||||
for (u32 n = SPop(&stack); n != 0; n = SPop(&stack), count -= 1)
|
||||
{
|
||||
assert(n.value == count);
|
||||
assert(n == count);
|
||||
}
|
||||
|
||||
assert(stack.top == null);
|
||||
assert(stack.top == &nil);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user