定义栈的结构体
//栈的结构体
typedef struct {
int* base; //栈底指针
int* top; //栈顶指针
int stacksize; //当前可使用的最大容量
}SqStack;
初始化
//初始化
int InitStack(SqStack* s) {
//构造一个空栈
s->base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));
if (!s->base)exit(0); //存储分配失败
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
printf("初始化成功!\n");
return 1;
}
返回栈顶元素
//返回栈顶元素
int GetTop(SqStack* s) {
if (s->top == s->base) {
return 0;
}
int e = *(s->top - 1);
return e;
}
插入新元素
//插入新元素
int Push(SqStack* s, int e) {
//栈满,追加空间
if (s->top - s->base >= s->stacksize) {
s->base = (int*)realloc(s->base, (s->stacksize + STACKINCREMENT) * sizeof(int));
if (!s->base) exit(0); //分配失败
s->top = s->base + s->stacksize;
s->stacksize += STACKINCREMENT;
}
*(s->top) = e;
s->top = s->top+1;
printf("成功插入元素%d!\n", e);
return 1;
}
删除栈顶元素
//删除栈顶元素
int Pop(SqStack* s) {
int e; //用e返回删除值
if (s->top == s->base) {
printf("是空栈!!\n");
return 0;
}
e = *(--s->top);
printf("成功删除栈顶元素%d\n", e);
return 1;
}
全部代码
#include <stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100 //存储空间初始分配量
#define STACKINCREMENT 10 //存储空间分配增量
//栈的结构体
typedef struct {
int* base; //栈底指针
int* top; //栈顶指针
int stacksize; //当前可使用的最大容量
}SqStack;
//初始化
int InitStack(SqStack* s) {
//构造一个空栈
s->base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));
if (!s->base)exit(0); //存储分配失败
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
printf("初始化成功!\n");
return 1;
}
//返回栈顶元素
int GetTop(SqStack* s) {
if (s->top == s->base) {
return 0;
}
int e = *(s->top - 1);
return e;
}
//插入新元素
int Push(SqStack* s, int e) {
//栈满,追加空间
if (s->top - s->base >= s->stacksize) {
s->base = (int*)realloc(s->base, (s->stacksize + STACKINCREMENT) * sizeof(int));
if (!s->base) exit(0); //分配失败
s->top = s->base + s->stacksize;
s->stacksize += STACKINCREMENT;
}
*(s->top) = e;
s->top = s->top+1;
printf("成功插入元素%d!\n", e);
return 1;
}
//删除栈顶元素
int Pop(SqStack* s) {
int e; //用e返回删除值
if (s->top == s->base) {
printf("是空栈!!\n");
return 0;
}
e = *(--s->top);
printf("成功删除栈顶元素%d\n", e);
return 1;
}
void main() {
SqStack S;
InitStack(&S);
Push(&S, 1);
Push(&S, 3);
Push(&S, 5);
Push(&S, 7);
Push(&S, 9);
printf("the top element is %d\n", GetTop(&S));
Pop(&S);
Pop(&S);
Pop(&S);
Pop(&S);
Pop(&S);
}
运行结果