HLPL/task4/stacks.c

116 lines
2.1 KiB
C

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "stacks.h"
STACK *init_stack(int size) {
if (size <= 0) {
return NULL;
}
STACK *buf;
buf = malloc(sizeof(STACK));
if (buf == NULL) {
fprintf(stderr, "Error allocating structure\n");
return NULL;
}
buf->st = malloc(sizeof(int) * size);
if (buf->st == NULL) {
fprintf(stderr, "Error allocating array\n");
free(buf);
return NULL;
}
buf->cnt = 0;
buf->size = size;
return buf;
}
void destroy_stack(STACK *s) {
free(s->st);
free(s);
}
void push(STACK *st, double val) {
if ((st->cnt) < (st->size)) {
st->st[st->cnt] = val;
(st->cnt)++;
} else {
fprintf(stderr, "Stack is full! Stack size is %d, value to add is %f\n",
st->size, val);
}
}
double pop(STACK *st) {
if ((st->cnt) > 0) {
(st->cnt)--;
return st->st[st->cnt];
} else {
fprintf(stderr, "Attempted to pop an empty stack\n");
return 0;
}
}
double top(STACK* st) {
if ((st->cnt) > 0) {
return st->st[(st->cnt)-1];
} else {
return 0;
}
}
// char stack
CHAR_STACK *init_char_stack(int size) {
if (size <= 0) {
return NULL;
}
CHAR_STACK *buf;
buf = malloc(sizeof(CHAR_STACK));
if (buf == NULL) {
fprintf(stderr, "Error allocating structure\n");
return NULL;
}
buf->st = malloc(sizeof(int) * size);
if (buf->st == NULL) {
fprintf(stderr, "Error allocating array\n");
free(buf);
return NULL;
}
buf->cnt = 0;
buf->size = size;
return buf;
}
void destroy_char_stack(CHAR_STACK *s) {
free(s->st);
free(s);
}
void char_push(CHAR_STACK *st, char val) {
if ((st->cnt) < (st->size)) {
st->st[st->cnt] = val;
(st->cnt)++;
} else {
fprintf(stderr, "Stack is full! Stack size is %d, value to add is %c\n",
st->size, val);
}
}
char char_pop(CHAR_STACK *st) {
if ((st->cnt) > 0) {
(st->cnt)--;
return st->st[st->cnt];
} else {
fprintf(stderr, "Attempted to pop an empty stack\n");
return 0;
}
}
char* char_top(CHAR_STACK* st) {
if ((st->cnt) > 0) {
return &(st->st[(st->cnt)-1]);
} else {
return NULL;
}
}