#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct Stack {
int* elements;
int max_size, top_index;
} Stack;
void init(Stack* s, int length) {
s->elements = (int*)malloc(sizeof(int) * length);
s->max_size = length;
s->top_index = -1;
}
void push(Stack* s, int val) {
if (s->top_index >= s->max_size-1) {
return;
}
s->top_index++;
s->elements[s->top_index] = val;
//printf("%d", top(s));
return;
}
void pop(Stack* s) {
if (s->top_index < 0) {
return;
}
s->top_index--;
return;
}
int top(Stack* s) { //输出栈顶元素
return s->elements[s->top_index];
}
int empty(Stack* s) { //空:1 非空:0
return s->top_index < 0;
}
void clear(Stack* s) {
free(s->elements);
free(s);
}
int main() {
Stack* numbers = (Stack*)malloc(sizeof(Stack));
init(numbers, 10);
clear(numbers);
system("pause");
return 0;
}
数据结构--栈(C language)
最新推荐文章于 2024-09-04 15:17:01 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)