//栈的数组实现(结构体封装版)
//-->栈被定义为结构体指针,具体数组也被定义为指针,栈动态新建
#define MAXSIZE 100
struct node
{
int capacity;//栈容量
int top;//栈顶
int* array;//数组存具体栈元素
};
void Push(struct node* stack,int element)
{
if(stack->top==MAXSIZE-1){
printf("The stack is full!\n");
return;
}
stack->array[++stack->top]=element;
}
void Pop(struct node* stack)
{
if(stack->top!=-1)
stack->top--;
}
void Top(struct node* stack)
{
if(stack->top!=-1)
printf("%d\n",stack->array[stack->top]);
else
printf("Empty stack!\n");
}
void PopandTop(struct node* stack)
{
if(stack->top!=-1)
printf("%d\n",stack->array[stack->top--]);
else
printf("Empty stack!\n");
}
int main()
{
//栈的新建
struct node* stack;
stack=(struct node* )malloc(sizeof(struct node));
//栈初始化(栈的array数组分配空间,但不用初始化)
stack->capacity=MAXSIZE;
stack->top=-1;//top初始化为-1
stack->array=(int *)malloc(sizeof(int)*MAXSIZE);
//Push
Push(stack,10);
//Pop
Pop(stack);
//Top
Top(stack);
//PopandTop
PopandTop(stack);
return 0;
}
stack的数组实现(结构体封装版)
最新推荐文章于 2025-07-11 21:09:53 发布