学习完《算法与数据结构》第三版第3章栈后进行代码实现
基于数组的栈是十分简单的,数组是横向存储的而栈是竖向的所以只需要我们将数组改成竖向就行了
让我们来看一下代码吧!
#include <stdio.h>
#include <stdlib.h>
#define max 100
typedef struct stack
{
int arr[max];//数组建立顺序栈
int top;//栈中元素个数
}stack;
//顺序栈初始化
void init(stack* s)
{
s->top = 0;//栈中个数初始化为0
}
//判断栈空
int empty(stack* s)
{
if (s->top > 0)
{
printf("栈中有元素");
return 0;
}
else
{
printf("这是一个空栈");
return 1;
}
}
//进栈
void push(stack* s)
{
if (s->top == max)
{
printf("栈满无法进栈");
}
else
{
int x;
printf("请输入要进栈的元素:");
scanf_s("%d",&x);
s->arr[s->top++] = x;//栈(数组)中的个数增加1
}
}
//出栈
int pop(stack* s)
{
if (s->top == 0)
{
printf("栈空无法出栈");
return 0;
}
else