CS2263/Final/FinalCode/adt/stack.h

73 lines
1.5 KiB
C
Raw Permalink Normal View History

2023-05-22 23:28:51 -03:00
#include <stdlib.h>
#include <stdio.h>
typedef struct stack {
int *array;
int total_size;
int size;
int top;
} Stack;
struct stack *createStack(int size) {
struct stack *s = malloc(sizeof(struct stack));
if (s == NULL) {
printf("Error: malloc failed\n");
return NULL;
}
s->array = malloc(sizeof(int) * size);
if (s->array == NULL) {
printf("Error: malloc failed\n");
return NULL;
}
s->total_size = size;
s->size = 0;
s->top = -1;
return s;
}
void deleteStack(struct stack *s) {
free(s->array);
free(s);
}
void printStack(struct stack *s) {
int i;
for (i = 0; i < s->size; i++) {
printf("%d ", s->array[i]);
}
printf("\n");
}
void push(struct stack *s, int item) {
if (s->size == s->total_size - 1) {
printf("Stack is full\n");
return;
}
s->array[s->size] = item;
s->top = item;
s->size++;
}
void pop(struct stack *s) {
if (s->top == -1) {
printf("Stack is empty\n");
return;
}
s->size--;
s->top = s->array[s->size];
}
int search(struct stack *s, int item) {
int i;
for (i = 0; i < s->total_size; i++) {
if (s->array[i] == item) {
return s->array[i];
}
}
return -1;
}
int peek(struct stack *s) {
if (s->top == -1) {
printf("Stack is empty\n");
return -1;
}
return s->top;
}