1、顺序栈
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#define ElemType int
#define STACK_INIT_SIZE 8
#define STACK_INC_SIZE 3
//顺序栈的定义
typedef struct SeqStack{
ElemType *base;
int capacity;
int top;
}SeqStack;
//初始化顺序栈
void init_SeqStack(SeqStack* st){
st->base = (ElemType*)malloc(sizeof(ElemType) * STACK_INIT_SIZE);
st->capacity = STACK_INIT_SIZE;
/*
top可为 -1 [入栈:先top++在放值 出栈: 先取值在top--]
也可为 0 [入栈:先放值在++ 出栈: 先--在放值]
*/
st->top = 0;
}
//判断栈是否已满[为真返回1 为假返回0 ]
int isFull(SeqStack* st){
return st->top >= st->capacity;
}
//判断栈是否为空[为真返回1 为假返回0 ]
int isEmpty(SeqStack* st){
return st->top == 0;
}
int inc_stack(SeqStack* st){
ElemType* newBase = (ElemType*)realloc(st->base,sizeof(ElemType) * (st->capacity + STACK_INC_SIZE));
if(newBase == NULL){
printf("内存空间不足,无法申请空间.\n");
return 0;
}
st->base = newBase;
st->capacity += STACK_INC_SIZE;
return 1;
}
//入栈
void push(SeqStack* st,ElemType e){
if(isFull(st) && !inc_stack(st)){
printf("栈空间已满,%d 不能入栈.\n",e);
return;
}
//如果top为-1 => st->base[++st->top] = e;
st->base[st->top++] = e;
}
//出栈
ElemType pop(SeqStack* st){
if(isEmpty(st)){
printf("栈空间已空,不能出栈.\n");
return;
}
//如果top为-1 => return st->base[st->top--];
return st->base[--st->top];
}
//得到栈顶元素,但不出栈
ElemType get_top(SeqStack* st){
if(isEmpty(st)){
printf("栈空间已空,不能出栈.\n");
return;
}
return st->base[st->top - 1];
}
//栈的长度
int length(SeqStack* st){
return st->top;
}
//清空栈
void clear(SeqStack* st){
st->top = 0;
}
//销毁栈
void destroy(SeqStack* st){
free(st->base);
st->capacity = st->top = 0;
}
//打印栈
void show_stack(SeqStack* st){
int i = st->top - 1;
for(i;i >= 0;i--){
printf("%d\n",st->base[i]);
}
printf("\n");
}
int main(){
SeqStack st;
init_SeqStack(&st);
int i = 1;
for(i;i <= 5;i++){
push(&st,i);
}
show_stack(&st);
pop(&st);
show_stack(&st);
return 0;
}
2、链栈
#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#define ElemType int
typedef struct StackNode{
ElemType data;
struct StackNode* next;
}StackNode;
typedef StackNode* LinkStack;
//注意 这里是二级指针
void initStack(LinkStack* st){
st = NULL;
}
StackNode* malloc_statckNode(ElemType e){
StackNode* p = (StackNode*)malloc(sizeof(StackNode));
assert(p != NULL);
p->data = e;
p->next = NULL;
}
//入栈
void push(LinkStack* st,ElemType e){
StackNode* p = malloc_statckNode(e);
if(*st == NULL){
//当前栈空间为空 ,新节点直接为栈顶
*st = p;
} else {
//新节点指向栈顶
p->next = *st;
//更换栈顶
*st = p;
}
}
//出栈
ElemType pop(LinkStack* st) {
if(*st == NULL){
printf("当前栈空间为空,不可出栈.\n");
return;
}
StackNode* top = *st;
*st = top->next;
ElemType e = top->data;
free(top);
return e;
}
//打印栈
void show(LinkStack* st){
LinkStack s = *st;
while(s != NULL){
printf("%d\n",s->data);
s = s->next;
}
printf("\n");
}
int main(){
LinkStack st;
//二级指针接收一级指针的地址
initStack(&st);
int i = 1;
for(i;i <= 5;i++){
push(&st,i);
}
show(&st);
pop(&st);
show(&st);
return 0;
}