刚学数据结构,目前还是一知半解,敬请批评指正,不胜感谢
参考博客:https://blog.csdn.net/qq_35852228/article/details/110851200
#include <stdio.h>
#include <stdlib.h>
#define maxsize 10//开始最大的空间
#define addsize 2//增加的空间
typedef int Elemtype;
typedef struct Sqstack
{
Elemtype* top;
Elemtype* base;
int stacksize;
}Sqstack;
int initstack(Sqstack* S)/*成功返回1,失败返回0*/
{
S->base = (Elemtype*)malloc(maxsize * sizeof(Elemtype));
if (!S->base) return 0;
S->top = S->base;
S->stacksize = maxsize;
return 1;
}
Elemtype stackempty(Sqstack* S)/*若为空返回1,不为空返回0*/
{
if (S->top == S->base)
{
return 1;
}
else
{
return 0;
}
}
Elemtype Push(Sqstack* S, Elemtype e)/*插入成功返回1,失败返回0*/
{
if (S->top - S->base == S->stacksize) //栈满,realloc函数扩充储存空间
{
S->base = (Elemtype*)realloc(S->base, (maxsize + addsize) * sizeof(Elemtype));
if (!S->base) { printf("插入失败\n"); return -1; }//扩充失败,返回-1
S->top = S->stacksize + S->base;
S->stacksize += addsize;
}
printf("请输入你要进栈的元素:");
scanf_s("%d", &e);
printf(" 插入成功\n");
*S->top++ = e;
return 1;
}
Elemtype pop(Sqstack* S, Elemtype e)//弹出成功返回1,失败返回0,并显示弹出元素
{
if (S->top == S->base)
{
printf("栈为空,弹出失败\n");
return 0;
}//栈空返回0
e = *(S->top-1);
printf("弹出成功,弹出的元素为:%d\n\n\n", e);
S->top--;
return 1;
}
Elemtype Gettop(Sqstack* S,Elemtype e)//获取栈顶元素
{
if (S->top == S->base) return 0;
e = *(S->top-1) ;
printf("\n获取成功,栈顶元素为%d\n", e);
return 1;
}
Elemtype Printfstack(Sqstack* S)//全部出栈,并打印栈中元素
{
if (S->base == S->top)
{
printf("栈为空\n");
return 0;
}
else
printf("栈中的元素为:\n");
for (; S->top != S->base; S->base++)
{
printf("%d\n", *S->base);
}
return 1;
}
void menu()
{
printf("******************************************\n");
printf("***** 欢迎来到航哥的顺序栈系统 *****\n");
printf("******************************************\n");
printf("***** 1.入栈 2.出栈 *****\n");
printf("***** 3.打印栈中元素 *****\n");
printf("***** 4.获取栈顶元素 *****\n");
printf("***** 0.退出系统 *****\n");
printf("******************************************\n");
}
int main()
{
Sqstack S;
int N;//需要操作的数字
if (initstack(&S))
{
printf(" ********初始化成功*******\n\n");
}
while (1)
{
menu();
printf("请输入你要输入的操作\n");
printf("1.入栈 2.出栈 3.打印栈中元素\n");
printf("4.获取栈中元素 0.退出系统 \n\n");
printf("请输入你要进行的操作:");
scanf_s("%d", &N);
if (N == 0)
{
printf("程序已退出,再见\n");
break;
}
switch (N)
{
case 0: break;
case 1:
Push(&S, N); break;
break;
case 2:
pop(&S, N); break;
case 3:
Printfstack(&S); break;
case 4:
Gettop(&S, N); break;
}
}
return 0;
}