Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct Stack {
- int *startaddress;
- int currentsize;
- int capacity;
- int initialcap;
- };
- void stack_destroy(struct Stack stack_dest){
- free(stack_dest.startaddress);
- }
- struct Stack stack_create(int size){
- int* array;
- array = malloc (size * sizeof(int));
- struct Stack new_stack;
- new_stack.startaddress = &array[0];
- new_stack.currentsize = 0;
- new_stack.capacity = size;
- new_stack.initialcap = size;
- printf("Stack successfully created...\n");
- return new_stack;
- }
- /*Need to pass pointer in order to change variables outside the function, also in pop*/
- void stack_push (struct Stack* ptr, int elem){
- if (ptr->currentsize >= ptr->capacity){
- printf("The stack was full, reallocating 2 times the size...\n");
- ptr->startaddress = realloc(ptr->startaddress, 2* (sizeof(int) * ptr->capacity));
- ptr->capacity *=2;
- }
- ptr->startaddress[ptr->currentsize] = elem;
- ptr->currentsize+=1;
- printf("Element added...\n");
- }
- int stack_pop (struct Stack* ptr){
- if(ptr->capacity > ptr->currentsize * 2 && ptr->capacity != ptr->initialcap){
- ptr->startaddress = realloc(ptr->startaddress, sizeof(int)/ ptr->capacity / 2);
- printf("Reduced stacksize, because it was bigger than needed.\n");
- }
- ptr->currentsize--;
- return ptr->startaddress[ptr->currentsize];
- }
- int stack_top (struct Stack stack){
- return stack.startaddress[stack.currentsize-1];
- }
- void stack_print(struct Stack stack){
- if(stack.currentsize == 0){
- printf("Stack is empty!\n");
- }
- else{
- printf("Printing all elements on commandline: \n");
- for(int temp = 1; temp < stack.currentsize; temp ++){
- printf("%d ",stack.startaddress[stack.currentsize-temp]);
- }
- printf("\n");
- }
- }
- int main(void){
- int size = 2;
- struct Stack stack1 = stack_create(size);
- struct Stack* ptr;
- ptr = &stack1;
- stack_push(ptr, 1);
- stack_push(ptr, 2);
- stack_push(ptr, 3);
- stack_push(ptr, 4);
- stack_push(ptr, 5);
- stack_push(ptr, 6);
- stack_push(ptr, 7);
- printf("Expecting 1 through 7:\n");
- stack_print(stack1);
- printf("\n");
- printf("Expecting 7:\n");
- printf("%d\n",stack_top(stack1));
- printf("\n");
- printf("Expecting 7:\n");
- printf("%d\n",stack_pop(ptr));
- printf("\n");
- printf("Expecting 6:\n");
- printf("%d\n",stack_top(stack1));
- printf("\n");
- printf("popping elements to reduce size...\n");
- printf("%d\n",stack_pop(ptr));
- printf("%d\n",stack_pop(ptr));
- printf("%d\n",stack_pop(ptr));
- printf("%d\n",stack_pop(ptr));
- printf("%d\n",stack_pop(ptr));
- stack_destroy(stack1);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement