编程实现栈的顺序存储和基本操作

2025-11-09 13:15:56

1、一、要求

编程实现栈的顺序存储和基本操作(初始化、入栈、取栈顶元素、出栈等)

编程实现栈的顺序存储和基本操作

2、二、代码

#include<stdio.h>

 #include<malloc.h>

 #define MAX 20

 typedef struct node

 {

 int data[MAX];

 int top;

 }Stack;

 void Initial_Stack(Stack * &s)//初始化栈

 {

 s=(Stack *)malloc(sizeof(Stack));

 s->top=-1;

 }

 void Empty_Stack(Stack *s)//判断栈是否为空

 {

 if(-1 == s->top)

 printf("栈空!\n");

 else

 printf("栈非空!\n");

 }

 void Creat_Stack(Stack * &s)//创建栈

 {

 int i=0;

 printf("Enter the data:\n");

 do{

 scanf("%d",s->data+i);

 s->top=i;

 i++;

 }while(i<MAX&&getchar()!='\n');

 }

 void Disp_Stack(Stack * &s)//打印栈

 {

 int i;

 for(i=s->top;i>=0;i--)

 printf("%d:  %d\n",s->top-i+1,s->data[i]);

 }

 void Pop_Stack(Stack * &s)//出栈

 {

 if(s->top==-1)

 {

 printf("Stack empty!\n");

 return;

 }

 s->top--;

 printf("After pop:\n");

 Disp_Stack(s);

 }

 int main()

 {

 Stack *S;

 Initial_Stack(S);

 Empty_Stack(S);

 Creat_Stack(S);

 Empty_Stack(S);

 printf("Initial stack:\n");

 Disp_Stack(S);

 Pop_Stack(S);

 return 0;

 }

编程实现栈的顺序存储和基本操作

3、三、运行结果

编程实现栈的顺序存储和基本操作

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢