Goofing around with a naive stack impl

This commit is contained in:
Dan Buch 2016-04-13 11:14:31 -04:00
parent 5d2b2e8e8e
commit b15e1ad794
2 changed files with 87 additions and 0 deletions

View File

@ -17,3 +17,4 @@ ex16
ex17 ex17
db.dat db.dat
ex17-ec ex17-ec
ex17-ec2

View File

@ -0,0 +1,86 @@
#include <stdio.h>
#include <stdlib.h>
#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;
}