usaa25/du3/program.c
2025-10-12 21:27:36 +02:00

68 lines
1.3 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_SIZE 10
struct stack{
float *values;
int size;
int capacity;
};
struct stack* create_stack (int capacity) {
struct stack* s = malloc (sizeof(struct stack));
if (s==NULL) {
printf("Error!\n");
exit(1);
}
s->values = malloc(capacity * sizeof(float));
if (s->values==NULL) {
printf("Error!\n");
free(s);
exit(1);
}
s->size = 0;
s->capacity = capacity;
return s;
}
void push_stack(struct stack* s, float value) {
if (s->size >= s->capacity) {
printf("Stack perepolnen!\n");
exit(1);
}
s->values[s->size] = value;
s->size++;
}
float pop_stack(struct stack* s) {
if (s->size <= 0) {
printf("Erroe!\n");
exit(1);
}
s->size--;
return s->values[s->size];
}
void print_stack(struct stack* stack) {
for (int i = 0; i<stack->size; i++) {
printf("%.2f", stack->values[i]);
}
printf("\n");
}
void destroy_stack (struct stack* s) {
free(s->values);
free(s);
}
int main() {
struct stack* novystack = create_stack(STACK_SIZE);
push_stack(novystack, 3.14);
push_stack(novystack, 2.71);
float x = pop_stack(novystack);
printf("Popped: %2.f\n", x);
print_stack(novystack);
destroy_stack(novystack);
return 0;
}