CS 245 Homework 1
- Due Date
- 4:00 pm Friday September 18
- Assignment Name
- stack
- File Names
- stack.c stack.h
Make the following changes to the stack data structure below (both stack.c and stack.h).
- When a item is pushed and the stack is full, resize it by using realloc to double the size of the array.
- Change the type of items stored in the stack from int to string (char *).
- When a string is pushed, push the actual argument (do not make a copy). It will be the responsiblity of the caller to copy a string before pushing if that is what's needed.
Turnin will compile my test program together with your stack implementation. Do not include a main program.
stack.h
// stack.c - An array implemention of the stack data structure.
#include <stdlib.h>
#include <assert.h>
#include "stack.h"
struct stack {
int size;
int *contents;
int top;
};
stack *stack_new(int size) {
stack *s = malloc(sizeof(struct stack));
if (s == NULL) return NULL;
s->size = size;
s->contents = malloc(size * sizeof(int));
if (s->contents == NULL) {
free(s);
return NULL;
}
s->top = -1;
return s;
}
void stack_push(stack *s, int value) {
assert(s->top < s->size - 1);
s->contents[++(s->top)] = value;
}
int stack_pop(stack *s) {
assert(s->top != -1);
return s->contents[s->top--];
}
bool stack_isempty(stack *s) {
return s->top == -1;
}
void stack_free(stack *s) {
free(s->contents);
free(s);
}
stack.h
// stack.c - An array implemention of the stack data structure. #ifndef STACK_H #define STACK_H typedef struct stack stack; stack *stack_new(int size); void stack_push(stack *s, int value); int stack_pop(stack *s); bool stack_isempty(stack *s); void stack_free(stack *s); #endif