栈
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct Stack {
int *data;
int top, size;
} Stack;
Stack *init(int n) {
Stack *s = (Stack *)malloc(sizeof(Stack));
s->data = (int *)malloc(sizeof(int) * n);
s->top = -1;
s->size = n;
return s;
}
int empty(Stack *s) {
return s->top == -1;
}
int top(Stack *s) {
return s->data[s->top];
}
int push(Stack *s, int val) {
if (s == NULL) return 0;
if (s->size == s->top - 1) return 0;
s->data[++(s->top)] = val;
return 1;
}
int pop(Stack *s) {
if (s == NULL) return 0;
if (empty(s)) return 0;
s->top -= 1;
return 1;
}
void clear(Stack *s) {
if(s == NULL) return ;
free(s->data);
free(s);
return ;
}
void output(Stack *s) {
printf("Stack : [");
for (int i = 0; i <= s->top; i++) {
i && printf(" ");
printf("%d", s->data[i]);
}
printf("]\n");
return ;
}
int main() {
srand(time(0));
#define MAX_OP 20
Stack *s = init(MAX_OP);
for (int i = 0; i < MAX_OP; i++) {
int val = rand() % 100;
int op = rand() % 4;
switch (op) {
case 0:
case 1:
case 2: {
printf("push %d to Stack = %d\n", val, push(s, val));
}break;
case 3: {
if (empty(s)) {
printf("fail to pop!\n");
} else {
printf("pop %d\n", top(s));
pop(s);
}
}break;
}
output(s), printf("\n");
}
return 0;
}