//arrayStack.c //John T. Rine //October 28, 2011 #include #include struct Stack { char *array; int top; int size; }; typedef struct Stack stack; int cntChars(char *); void createStack(stack *, int); void push(stack *, char); char pop(stack *); int isEmpty(stack *); int isFull(stack *); int main(int argc, char **argv) { int i; int count; stack newStack; char stringArray[200]; printf("Enter a string: "); gets(stringArray); count = cntChars(stringArray); createStack(&newStack, count); if(isEmpty(&newStack)) printf("Stack is empty\n"); else printf("Stack is not empty\n"); for(i = 0; i < count; i++) { push(&newStack,stringArray[i]); printf("The character going into tos is: %c\n", newStack.array[i]); } if(isEmpty(&newStack)) printf("Stack is empty\n"); else printf("Stack is not empty\n"); for(i = 0; i < count; i++) printf("The character in tos is: %c\n", pop(&newStack)); for(i = 0; i < count; i++) { push(&newStack,stringArray[i]); printf("The character going into tos is: %c\n", newStack.array[i]); } push(&newStack,'H'); return 0; } int cntChars(char *inputString) { // returned value "count" does not include '\0' int count = 0; while(*(inputString + count) != '\0') ++count; return(count); } void createStack(stack *stackVar, int size) { char *array; array = (char *)malloc(sizeof(char) * size); if (array == NULL) { fprintf(stderr, "Not enough memory to create the stack.\n"); exit(1); } stackVar->array = array; stackVar->size = size; stackVar->top = -1; } int isEmpty(stack *stackVar) { return stackVar->top < 0; } int isFull(stack *stackVar) { return stackVar->top >= stackVar->size - 1; } void push(stack *stackVar, char element) { if (isFull(stackVar)) { fprintf(stderr, "Can't push on the stack is full\n"); exit(1); } stackVar->array[++stackVar->top] = element; } char pop(stack *stackVar) { if (isEmpty(stackVar)) { fprintf(stderr, "Can't pop from stack; stack is empty\n"); exit(1); } return stackVar->array[stackVar->top--]; }