1: #include <stdio.h>2: #include <malloc.h>3:4: #define INCREMENT 305:6: int capacity = 0;7: int size = 0;//this will also be used as a index8: //number of elements popped,9: //used in reducing the size of the array10: int popCount = 0;11:12: int push(int **array,int val)13: {14: (*array)[size++] = val;15: if(size == capacity)16: capacityChange(array,capacity+INCREMENT);17:18: return 1;19: }20:21: int pop(int **array)22: {23: size-=1;//index is one less than the size24: if(size < 0)25: return 0;26: else27: {28: popCount++;29: if(popCount == INCREMENT)30: {31: capacityChange(array,capacity-popCount);32: popCount = 0;33: }34: return (*array)[size];35: }36: }37:38: int capacityChange(int **array,int ncapacity)39: {40: int i ;41: *array = realloc(*array,sizeof(int)*ncapacity);42:43: if(ncapacity > capacity)44: printf("increasing capacity to %d \n",ncapacity);45: else if(ncapacity < capacity)46: printf("decreasing the capacity to %d \n",ncapacity);47:48: capacity = ncapacity;49:50: return 1;51: }52:53: main()54: {55: int i;56: int *array = (int*)malloc(sizeof(int) * INCREMENT);57: capacity = INCREMENT;58:59: for(i = 0 ; i < 31 ; i++)60: push(&array,i);61:62: printf("size is %d \n",size);63: do64: {65: printf("poping the top %d \n", pop(&array));66: }while(size);67:68: printf("size is %d \n",size);69: printf("capacity is is %d \n",capacity);70: getchar();71: }
Sunday, June 6, 2010
Stack Using Dynamic Array in C
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment