参考严蔚敏《数据结构》第二版代码实现:
#define _CRT_SECURE_NO_WARINING
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int* base; //栈底指针
int* top; //栈顶指针
int stacksize; //可用最大容量
}Sqstack;
int InitStack(Sqstack *S)
{
S->base = (Sqstack*)malloc(MAXSIZE * sizeof(Sqstack));
if (!S->base)exit(-2);
S->top = S->base;
S->stacksize = MAXSIZE;
return 1;
}
int Push(Sqstack* S, int e)
{
*S->top = e;
S->top++;
return 1;
}
int Pop(Sqstack* S, int e)
{
S->top--;
e = *S->top;
return e;
}
int main()
{
Sqstack L;
InitStack(&L);
int e;
int a=0;
printf("入栈:");
scanf_s("%d", &e);
Push(&L, e);
a = Pop(&L, a);
printf("出栈:%d", a);
return 0;
}
无栈底指针:
#define _CRT_SECURE_NO_WARINING
#include <stdio.h>
#include <stdlib.h>
struct SqStack {
int* data;//数据
int top;
int capacity;//最大容量
};
int InitStack(struct SqStack *S,int capacity)
{
S->capacity = capacity;
S->data = (int*)malloc(sizeof(int) * capacity);
S->top = 0;
return 1;
}
int isFull(const struct SqStack* ps)
{
return ps->top == ps->capacity;
}
int isEmpty(const struct SqStack* ps)
{
return ps->top == 0;
}
int Push(struct SqStack* s, int e)
{
if (isFull(s))
{
return 0;
}
else
{
scanf_s("%d", &e);
s->top = e;
s->top++;
return 1;
}
}
int Pop(struct SqStack* s, int *e)
{
if (isEmpty(s))
{
return 0;
}
else
{
s->top--;
*e = s->top;
return *e;
}
}
int main()
{
struct SqStack S;
int e = 0;
InitStack(&S, 5);
Push(&S, e);
e=Pop(&S, &e);
printf("%d", e);
return 0;
}