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:
parent
4c6ff8bb23
commit
33cf63a30e
|
@ -1,3 +1,4 @@
|
|||
*.exe
|
||||
*.o
|
||||
*.sh
|
||||
*.out
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
@ -112,4 +121,4 @@ void printStack(Stack s){
|
|||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
|
Loading…
Reference in New Issue