C语言每次都用到栈都要写一次,太麻烦了,为了方便,先存个模板吧,以后直接复制过来用了。
头文件 stack.h
根据栈内要存的数据的具体类型,更改 stack.h 中的ElementType即可(C语言没有泛型,难受 o(一︿一+)o)。
#include <stdbool.h>
typedef int ElementType;
typedef struct Stack {
int size;
int capacity;
ElementType *data;
} * Stack;
Stack create_stack(int capacity); // 创建栈
void delete_stack(Stack s); // 删除栈
bool push(Stack s, ElementType e); // 入栈
ElementType pop(Stack s); // 出栈
ElementType top(Stack s); // 访问栈顶元素
bool is_full(Stack s); // 判断栈是否满
bool is_empty(Stack s); // 判断栈是否为空
void make_stack_empty(Stack s); // 清空栈内元素
文件 stack.c
#include "stack.h"
#include <malloc.h>
#include <stdio.h>
Stack create_stack(int capacity)
{
if (capacity <= 0) {
fprintf(stderr, "stack capacity is wrong!");
return NULL;
}
Stack s = malloc(sizeof(struct Stack));
s->data = malloc(capacity * sizeof(ElementType));
s->capacity = capacity;
s->size = 0;
return s;
}
void delete_stack(Stack s)
{
if (s != NULL) {
if (s->data != NULL)
free(s->data);
free(s);
}
}
bool push(Stack s, ElementType e)
{
if (s == NULL) {
fprintf(stderr, "stack to push is NULL!\n");
return false;
}
if (is_full(s)) {
fprintf(stderr, "stack to push has been full!\n");
return false;
}
s->data[s->size++] = e;
return true;
}
ElementType pop(Stack s)
{
if (s == NULL) {
fprintf(stderr, "stack to pop is NULL!\n");
return false;
}
if (is_empty(s)) {
fprintf(stderr, "stack to pop is empty!\n");
return false;
}
return s->data[--s->size];
}
ElementType top(Stack s)
{
if (s == NULL) {
fprintf(stderr, "stack is NULL!\n");
return false;
}
if (is_empty(s)) {
fprintf(stderr, "stack is empty!\n");
return false;
}
return s->data[s->size - 1];
}
bool is_full(Stack s) { return s->size == s->capacity; }
bool is_empty(Stack s) { return s->size == 0; }
void make_stack_empty(Stack s) { s->size = 0; }