Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdbool.h>
- #include <stdlib.h>
- /**
- * Stack
- */
- typedef struct Stack {
- int maxSize;
- void **values;
- int top;
- } Stack;
- Stack *stack_create(int maxSize) {
- Stack *stack = malloc(sizeof(Stack));
- stack->maxSize = maxSize;
- void **values = malloc(sizeof(void*) * maxSize);
- stack->values = values;
- stack->top = 0;
- return stack;
- }
- bool stack_is_empty(Stack *stack) {
- return stack->top == 0;
- }
- bool stack_is_full(Stack *stack) {
- return stack->top == stack->maxSize;
- }
- void *stack_push(Stack *stack, void *value) {
- if (stack_is_full(stack)) {
- return NULL;
- }
- stack->values[stack->top++] = value;
- return value;
- }
- void *stack_pop(Stack *stack) {
- if (stack_is_empty(stack)) {
- return NULL;
- }
- return stack->values[--stack->top];
- }
- int main(int argc, char** argv) {
- Stack *stack = stack_create(2);
- int *x1 = malloc(sizeof(int));
- *x1 = 10;
- stack_push(stack, x1);
- int *x2 = malloc(sizeof(int));
- *x2 = 20;
- stack_push(stack, x2);
- int *x3 = malloc(sizeof(int));
- *x3 = 30;
- bool itWorks = stack_push(stack, x3) == NULL
- && *(int*) stack_pop(stack) == 20
- && *(int*) stack_pop(stack) == 10
- && stack_pop(stack) == NULL;
- printf("%s", itWorks ? "IT WORKS! :)" : "IT DOESN'T WORK :(");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement