diff --git a/lcthw-remnants-2/.gitignore b/lcthw-remnants-2/.gitignore index 8072b4b..976020d 100644 --- a/lcthw-remnants-2/.gitignore +++ b/lcthw-remnants-2/.gitignore @@ -17,3 +17,4 @@ ex16 ex17 db.dat ex17-ec +ex17-ec2 diff --git a/lcthw-remnants-2/ex17-ec2.c b/lcthw-remnants-2/ex17-ec2.c new file mode 100644 index 0000000..58a7f02 --- /dev/null +++ b/lcthw-remnants-2/ex17-ec2.c @@ -0,0 +1,86 @@ +#include +#include + +#define MAX_STACK 1024 +#define STACK_SENTINEL -1 + +struct Stack { + int l[MAX_STACK]; +}; + +struct Stack *Stack_create() +{ + struct Stack *s = malloc(sizeof(struct Stack)); + if(!s) { return NULL; } + + int i = 0; + + for(i = 0; i < MAX_STACK; i++) { + s->l[i] = STACK_SENTINEL; + } + + return s; +} + +int Stack_push(struct Stack *s, int v) +{ + if(v <= STACK_SENTINEL) { + return STACK_SENTINEL; + } + + int i = 0; + for(i = 0; i < MAX_STACK; i++) { + if(s->l[i] == STACK_SENTINEL) { + s->l[i] = v; + return i; + } + } + + return STACK_SENTINEL; +} + +int Stack_pop(struct Stack *s) +{ + int i = 0; + int v = 0; + for(i = 0; i < MAX_STACK; i++) { + if(s->l[i] == STACK_SENTINEL) { + v = s->l[i-1]; + s->l[i-1] = STACK_SENTINEL; + return v; + } + } + + return STACK_SENTINEL; +} + +int Stack_size(struct Stack *s) +{ + int i = 0; + for(i = 0; i < MAX_STACK; i++) { + if(s->l[i] == STACK_SENTINEL) { + return i; + } + } + + return STACK_SENTINEL; +} + +int main(int argc, char *argv[]) +{ + struct Stack *s = Stack_create(); + + printf("size: %d\n", Stack_size(s)); + Stack_push(s, 10); + Stack_push(s, 20); + Stack_push(s, 40); + + printf("size: %d\n", Stack_size(s)); + printf("pop: %d\n", Stack_pop(s)); + printf("pop: %d\n", Stack_pop(s)); + printf("size: %d\n", Stack_size(s)); + printf("pop: %d\n", Stack_pop(s)); + printf("pop: %d\n", Stack_pop(s)); + + return 0; +}