/* * Code example for CP264 Data Structures II * array stack * HBF */ #include #define MAX 10 void push(int stack[], int *top, int val); void pop(int stack[], int *top); int peek(int stack[], int top); void display_stack(int stack[], int top); int main() { int stack[MAX]; int top = -1; printf("push:\n"); push(stack, &top, 1); push(stack, &top, 2); push(stack, &top, 3); printf("display:\n"); display_stack(stack, top); printf("\npeek:%d\n", peek(stack, top)); printf("pop\n"); pop(stack, &top); printf("display:\n"); display_stack(stack, top); return 0; } void push(int stack[], int *top, int val) { if (*top == MAX-1) { printf("\n STACK OVERFLOW"); } else { *top = *top + 1; stack[*top] = val; } } void pop(int stack[], int *top) { if (*top == -1) { printf("\n STACK UNDERFLOW"); } else { *top = *top - 1; } } int peek(int stack[], int top) { if (top == -1) { printf("\n STACK IS EMPTY"); return -1; } else return (stack[top]); } void display_stack(int stack[], int top) { int i; if (top == -1) printf("\nSTACK IS EMPTY"); else { for (i = top; i >= 0; i--) { printf("%d ", stack[i]); } } } /* push: display: 3 2 1 peek:3 pop display: 2 1 */