#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct stack {
int* data;
int size, top;
}stack;
stack* initstack(int n) {
stack* s = (stack*)malloc(sizeof(stack));
s->data = (int*)malloc(sizeof(int) * n);
s->size = n;
s->top = -1;
return s;
}
int empty(stack *s) {
return s->top == -1;
}
int top(stack* s) {
if (empty(s))return 0;
return s->data[s->top];
}
int push(int val, stack* s) {
if (s->top + 1 == s->size)return 0;
s->top += 1;
s->data[s->top]=val;
return 1;
}
int pop(stack* s) {
if (empty(s))return 0;
s->top -= 1;
return 1;
}
void outputstack(stack* s) {
printf("stack:");
for (int i = s->top; i >= 0; --i) {
printf("%4d", s->data[i]);
}
printf("\n\n");
}
void clearstack(stack* s) {
if (empty(s))return ;
free(s->data);
free(s);
return;
}
int main() {
srand(time(0));
#define MAX_OP 10
stack* s = initstack(5);
for (int i = 0; i < MAX_OP; i++) {
int op = rand() % 3, val = rand() % 100;
switch (op) {
case 0:
printf("pop stack,item=%d\n",top(s));
pop(s);
break;
case 1:
case 2:
printf("push stack,item=%d\n", val);
push(val,s);
break;
}
outputstack(s);
}
clearstack(s);
return 0;
}
栈初始化实现
最新推荐文章于 2024-09-08 17:41:31 发布