box-o-sand/lcthw-remnants-2/ex17-ec2.c

87 lines
1.4 KiB
C
Raw Normal View History

2016-04-13 15:14:31 +00:00
#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;
}