5 #include "cgds/Stack.h"
7 void _stack_init(Stack
* stack
, size_t dataSize
)
10 stack
->dataSize
= dataSize
;
14 Stack
* _stack_new(size_t dataSize
)
16 Stack
* stack
= (Stack
*) safe_malloc(sizeof (Stack
));
17 _stack_init(stack
, dataSize
);
21 Stack
* stack_copy(Stack
* stack
)
23 // since a stack is a single-linked list, an auxiliary storage is required
24 void** tmpStorage
= (void**) malloc(stack
->size
* sizeof (void*));
25 StackCell
* stackCell
= stack
->top
;
26 for (UInt i
= 0; i
< stack
->size
; i
++)
28 tmpStorage
[stack
->size
- 1 - i
] = stackCell
->data
;
29 stackCell
= stackCell
->previous
;
31 // now transfer tmpStorage contents (pushed in right order) in a new stack
32 Stack
* stackCopy
= _stack_new(stack
->dataSize
);
33 for (UInt i
= 0; i
< stack
->size
; i
++)
34 _stack_push(stackCopy
, tmpStorage
[i
]);
39 Bool
stack_empty(Stack
* stack
)
41 return (stack
->size
== 0);
44 UInt
stack_size(Stack
* stack
)
49 void _stack_push(Stack
* stack
, void* data
)
51 StackCell
* newStackTop
= (StackCell
*) safe_malloc(sizeof (StackCell
));
52 newStackTop
->data
= safe_malloc(stack
->dataSize
);
53 memcpy(newStackTop
->data
, data
, stack
->dataSize
);
54 newStackTop
->previous
= stack
->top
;
55 stack
->top
= newStackTop
;
59 void* _stack_top(Stack
* stack
)
61 return stack
->top
->data
;
64 void stack_pop(Stack
* stack
)
66 StackCell
* toTrash
= stack
->top
;
67 stack
->top
= stack
->top
->previous
;
68 safe_free(toTrash
->data
);
73 void stack_clear(Stack
* stack
)
75 while (stack
->size
> 0)
77 _stack_init(stack
, stack
->dataSize
);
80 void stack_destroy(Stack
* stack
)