Implement PUSH, POP, and TRAVERSE operations on a stack using array.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Stack_ {
int size;
int top;
int *data;
} Stack;
void intit_stack(Stack* s, int n) {
s->size = n;
s->top = 0;
s->data = (int *) malloc(n*sizeof(int));
}
void free_stack(Stack* s) {
free(s->data);
s->size = s->top = 0;
s->data = NULL;
}
void push(Stack* s, int val) {
if (s->top == s->size) {
fprintf(stderr, "Stack overflow\n");
exit(1);
}
s->data[s->top++] = val;
}
int pop(Stack* s) {
if (s->top == 0) {
fprintf(stderr, "Stack underflow\n");
exit(1);
}
return s->data[--s->top];
}
int empty(Stack* s) {
return s->top == 0;
}
int full(Stack* s) {
return s->top == s->size;
}
void traverse(Stack* s, void (*fun)(int)) {
int i;
for (i=s->top-1; i>=0; i--)
fun(s->data[i]);
}
void print(int x) {
printf("%d => ", x);
}
int main() {
Stack stack;
int x;
int i;
srand(time(NULL));
intit_stack(&stack, 100);
for (i=0; i<10; i++) {
x = rand() % 100;
printf("Push: %d\n", x);
push(&stack, x);
}
printf("\nTraverse the stack:\n");
traverse(&stack, print);
printf("\n\n");
while (!empty(&stack)) {
x = pop(&stack);
printf("Pop: %d\n", x);
}
free_stack(&stack);
return 0;
}
Comments
Leave a comment