对于栈的内存分布简单画一个图:
top指向最上方的元素,存入时只能从下往上,取出时只能从上往下
可以理解为单一入口的,只能从上方进出
#include<stdio.h>
#include<malloc.h>
#define max_size 5
typedef struct stack
{
int top;
int data[max_size];
}stack,*stackptr;
stackptr creat()
{
stackptr p = (stackptr)malloc(sizeof(stack));
p->top = -1;
return p;
}
void push(stackptr p,int data)
{
if (p->top == max_size)
{
printf("the stack is full\n");
return ;
}
p->top++;
p->data[p->top] = data;
}
void pop(stackptr p)
{
if (p->top < 0)
{
printf("the stack is empty\n");
return;
}
p->top--;
}
void print(stackptr p)
{
int i;
for (i = 0; i <= p->top; i++)
{
printf("%d", p->data[i]);
}
printf("\n");
}
int main()
{
stackptr p = creat();
int i;
for (i = 0; i < 7; i++)
{
push(p,i);
print(p);
}
for (i = 0; i < 7; i++)
{
pop(p);
print(p);
}
return 0;
}
运行结果:
0
01
012
0123
01234
012345
the stack is full
012345
01234
0123
012
01
0
the stack is empty