95 lines
1.5 KiB
C
95 lines
1.5 KiB
C
#include "data_structures.h"
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#define STARTING_SIZE 8
|
|
|
|
void initList(list **l) {
|
|
list *li;
|
|
li = (list *)malloc(sizeof(list));
|
|
if (!li) {
|
|
printf("Failed to allocate memory for list\n");
|
|
exit(1);
|
|
}
|
|
|
|
li->size = 0;
|
|
li->capacity = STARTING_SIZE;
|
|
li->head = -1;
|
|
li->tail = 0;
|
|
li->arr = (char *)malloc(STARTING_SIZE * sizeof(char));
|
|
if (!li->arr) {
|
|
printf("Failed to allocate memory for arr in list\n");
|
|
exit(1);
|
|
}
|
|
|
|
*l = li;
|
|
}
|
|
|
|
void pushs(list *l, char c) {
|
|
if (l->head + 1 == l->capacity) {
|
|
l->capacity <<= 1;
|
|
l->arr = (char *)realloc(l->arr, l->capacity * sizeof(char));
|
|
}
|
|
|
|
l->head += 1;
|
|
l->size += 1;
|
|
l->arr[l->head] = c;
|
|
}
|
|
|
|
char pops(list *l) {
|
|
if (l->size == 0 || l->head == -1) {
|
|
return -1;
|
|
}
|
|
|
|
l->head -= 1;
|
|
l->size -= 1;
|
|
return l->arr[l->head + 1];
|
|
}
|
|
|
|
void enqueues(list *l, char c) {
|
|
pushs(l, c);
|
|
}
|
|
|
|
char dequeues(list *l) {
|
|
if (l->size == 0 || l->tail == l->head){
|
|
return -1;
|
|
}
|
|
|
|
l->tail += 1;
|
|
l->size -= 1;
|
|
return l->arr[l->tail - 1];
|
|
}
|
|
|
|
char* contents(list *l) {
|
|
char *out = (char*)malloc(l->size * sizeof(char) + 1);
|
|
memcpy(out, l->arr + l->tail, l->size + 1);
|
|
out[l->size] = '\0';
|
|
|
|
return out;
|
|
}
|
|
|
|
char* contentb(list *l) {
|
|
char *out = (char*)malloc(l->size * sizeof(char) + 1);
|
|
for (int i = 0; i<l->size; i++){
|
|
int index = l->head - i;
|
|
out[i] = l->arr[index];
|
|
}
|
|
out[l->size] = '\0';
|
|
|
|
return out;
|
|
}
|
|
|
|
void clears(list *l) {
|
|
l->head=-1;
|
|
l->size=0;
|
|
l->tail=0;
|
|
}
|
|
|
|
void freelist(list *l) {
|
|
free(l->arr);
|
|
free(l);
|
|
}
|
|
|