//顺序栈的代码实现
#include <stdio.h>
#include <malloc.h>
#include <windows.h>
#include <stdlib.h>
#define max 100
typedef struct stack
{
int a[max];
int tap;
}stack,*Pstack;
//函数区 *******************************************
//等待动画
void waiting(void)
{
int index = 0;
int count = 0;
char ch[] = {'|','\\','-','/'};
while(count < 10)
{
putchar(ch[index]);
index++;
if(index >= 4)
{
index = 0;
}
Sleep(200);
printf("\b");
count++;
}
return;
}
//初始化顺序栈
Pstack init(void)
{
Pstack s;
s = (Pstack)malloc(sizeof(stack)); //分配内存空间
if(s) //如果分配成功则......
{
s->tap = -1;
}
return s;
}
//判断是否空栈
int whether_empty(Pstack s)
{
if(s->tap == -1) //空栈返回 1
{
return 1;
}
else //非空栈返回 0
{
return 0;
}
}
//入栈
int enter_stack(Pstack s) //入栈成功返回 1,否则返回 0
{
int x;
//先判断是否满栈
if(s->tap == max - 1)
{
printf("the stack is full!\n");
return 0; //满栈无法插入
}
else
{
int num;
printf("请输入你要输入的元素数(少于100个):");
scanf("%d",&num);
for(int i = 0 ; i < num ; i++)
{
printf("请输入元素:");
scanf("%d",&x);
s->a[++s->tap] = x; //将x赋值进顺序表
}
printf("请稍等......\n");
waiting();
printf("入栈成功!!!2秒后将返回菜单界面......\n");
waiting();
return 1; //进栈成功则返回 1
}
}
//出栈
int quit_stack(Pstack s,int* x)
{
//出栈成功则返回 1
if(whether_empty(s))
{//空栈不能出栈
printf("this stack is empty!\n");
return 0;
}
else
{
*x = s->a[s->tap]; //赋值
s->tap--;
printf("出栈的元素为:%d",*x);
return 1; //出栈成功则返回 1
}
}
//取栈顶
int get_top(Pstack s)
{
int x;
if(whether_empty(s))
{
printf("empty stack!\n");
printf("\n2秒后返回菜单......\n");
waiting();
return 0;
}
else
{
x = s->a[s->tap];
printf("%d\n",x);
printf("\n2秒后返回菜单......\n");
waiting();
return 1;
}
}
//销毁栈
void destroy_stack(Pstack s)
{
if(s)
{
free(s);
s = NULL;
}
printf("销毁成功,结束任务!\n");
printf("正在退出程序......\n");
waiting();
return;
}
//查看栈
void check_stack(Pstack s)
{
if(s->tap == -1)
{
printf("empty stack!!!\n");
printf("\n2秒后返回菜单......\n");
waiting();
return;
}
int loc = -1;
while(loc < s->tap)
{
printf("%d ",s->a[++loc]);
}
printf("\n2秒后返回菜单......\n");
waiting();
return;
}
//主函数 **************************************************
int main(void)
{
Pstack s;
s = init();
int a;
rpt:
printf("查看顺序栈:输入1\n入栈:输入2\n获取栈顶元素:输入3\n销毁顺序栈并退出程序:输入4\n");
printf("请输入:");
scanf("%d",&a);
switch(a)
{
case 1:
check_stack(s); //查看顺序栈的元素
break;
case 2:
enter_stack(s);
break;
case 3:
get_top(s);
break;
case 4:
destroy_stack(s);
goto end;
break;
default:
printf("illegal input!!!\n");
}
system("cls");
goto rpt;
end:
return 0;
}
这是一个简易的顺序栈小程序,主要实现了写入、输出、读取栈顶元素和销毁栈的功能。