Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct Stack{
- int count;
- int capacity;
- int *elements;
- };
- struct Stack StackCreate(void){
- struct Stack s = {
- .count = 0,
- .capacity = 0,
- .elements = 0
- };
- return s;
- }
- void StackExpand(struct Stack *s){
- if(s->capacity == 0) {
- s->capacity++;
- }
- s->capacity *= 2;
- int *temp = realloc(s->elements, sizeof(s->elements[0]) * s->capacity);
- if(temp == NULL){
- fprintf(stderr, "Realloc failed to expand stack.\n");
- exit(1);
- } else {
- s->elements = temp;
- }
- }
- void StackShrink(struct Stack *s){
- s->capacity = (int)(s->capacity / 1.5f);
- int *temp = realloc(s->elements, sizeof(s->elements[0]) * s->capacity);
- if(temp == NULL){
- fprintf(stderr, "Realloc failed to shrink stack.\n");
- exit(1);
- } else {
- s->elements = temp;
- }
- }
- void StackPush(struct Stack *s, int input){
- if(s->count == s->capacity){
- StackExpand(s);
- }
- s->elements[s->count++] = input;
- }
- int StackPop(struct Stack *s){
- if(s->capacity >= s->count * 2.5f) {
- StackShrink(s);
- }
- if(s->count > 1){
- s->count--;
- return (s->elements[s->count]);
- } else {
- fprintf(stderr, "Popped empty stack.\n");
- return 0;
- }
- }
- void StackPrint(struct Stack *s){
- printf("[");
- for(int i = 0; i < s->count; ++i){
- printf("%X", s->elements[i]);
- if(i < s->count-1){
- printf(",");
- }
- }
- printf("]\n");
- printf("Count: %i\n", s->count);
- printf("Capacity: %i\n", s->capacity);
- }
Add Comment
Please, Sign In to add comment