Added a tester file and used pointers for stacks.

Changed arguments for stack functions to pointers, for ease of use!
This commit is contained in:
Andrew Lalis 2017-05-22 15:26:21 +02:00
parent 4c6ff8bb23
commit 33cf63a30e
3 changed files with 45 additions and 20 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
*.exe
*.o
*.sh
*.out

View File

@ -38,6 +38,15 @@ typedef struct {
int* items;
} Stack;
/*
Stack Functions:
*/
Stack newStack();
void freeStack(Stack *s);
void pushToStack(int item, Stack *s);
int popFromStack(Stack *s);
void printStack(Stack s);
/*
Stack Creation:
Creates a new stack with a default size defined above.
@ -55,48 +64,48 @@ Stack newStack(){
Stack Deallocation:
Safely deallocates memory assigned to the stack's list.
*/
void freeStack(Stack s){
free(s.items);
void freeStack(Stack *s){
free(s->items);
}
/*
Stack Push:
Pushes an item onto a stack. If there is no more room, more memory will be allocated to accommodate the extra item.
*/
void pushToStack(int item, Stack s){
void pushToStack(int item, Stack *s){
//It is safe to push to the stack.
if (s.top < s.size){
s.items[s.top] = item;
if (s->top < s->size){
s->items[s->top] = item;
} else {
//There was not enough space, so we must double size.
s.size *= 2;
s.items = realloc(s.items, s.size*sizeof(int));
assert(s.items != NULL);
s.items[s.top] = item;
s->size *= 2;
s->items = realloc(s->items, s->size*sizeof(int));
assert(s->items != NULL);
s->items[s->top] = item;
}
s.top++;
s->top++;
}
/*
Stack Pop:
Pops an item from the top of the stack, if it exists, or zero otherwise. Size will be checked to see if it is needed to reduce the size of the array.
*/
int popFromStack(Stack s){
int popFromStack(Stack *s){
int result;
//Check if at least one item exists in the list.
if (s.top > 0){
s.top--;
result = s.items[s.top];
if (s->top > 0){
s->top--;
result = s->items[s->top];
} else {
//The stack is empty.
result = 0;
fprintf(syserr, "STACK EMPTY");
fprintf(stderr, "STACK EMPTY");
}
//Check if the items array size can be reduced.
if (s.top < (s.size / 2) && (s.size > STACK_SIZE_DEFAULT)){
s.size /= 2;
s.items = realloc(s.items, s.size*sizeof(int));
assert(s.items != NULL);
if (s->top < (s->size / 2) && (s->size > STACK_SIZE_DEFAULT)){
s->size /= 2;
s->items = realloc(s->items, s->size*sizeof(int));
assert(s->items != NULL);
}
return result;
}

15
test.c Normal file
View File

@ -0,0 +1,15 @@
#include "source/handyalgs.h"
#include <stdio.h>
int main(int argc, char* argv[]){
Stack s = newStack();
for (int i = 2; i < 500; i+=3){
pushToStack(i, &s);
}
printStack(s);
for (int i = 0; i < 100; i++){
popFromStack(&s);
}
printStack(s);
}