[题目]
实验二 栈·队列操作
一、实验目的
a.掌握栈这种数据结构特性及其主要存储结构,并能在现实生活中灵活运用。
b.掌握队列这种数据结构特性及其主要存储结构,并能在现实生活中灵活运用。
c.了解和掌握递归程序设计的基本原理和方法。
二、实验内容
d.栈的顺序存储结构及实现。
e.循环队列(即队列的顺序存储结构)实现。
三、原代码(注释)
c.栈的顺序存储结构及实现。
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20 /* 数组最大界限 */
typedef int ElemType; /* 数据元素类型 */
typedef struct
{ ElemType a[MAXSIZE]; /* 一维数组子域 */
int top; /* 栈顶指针子域 */
}SqStack; /* 栈的顺序结构体类型 */
SqStack s1;
/* 函数声明 */
void init_s(SqStack *s); /* 初始化空栈 * /
void out_s(SqStack s); /* 输出栈的内容 */
void push(SqStack *s,ElemType e); /* 进栈函数 */
ElemType pop(SqStack *s); /* 出栈函数 */
/* 主函数 */
main()
{ int k; ElemType e,x; char ch;
init_s( &s1); /* 初始化一个空栈 */
do { printf("\n\n\n");
printf("\n\n 1. 数据元素e进栈 ");
printf("\n\n 2. 出栈一个元素,返回其值");
printf("\n\n 3. 结束程序运行");
printf("\n======================================");
printf("\n 请输入您的选择 (1,2,3)");
scanf("%d",&k);
switch(k)
{ case 1:{ printf("\n 进栈 e=?"); scanf("%d",&e);
push( &s1,e); out_s( s1 );
} break;
case 2:{ x= pop( &s1);
printf("\n出栈元素 : %d", x);
out_s( s1 );
} break;
case 3: exit(0);
} /* switch */
printf("\n ----------------");
}while(k>=1 && k<3);
printf("\n 再见!")
printf(“\n 打回车键,返回。“); ch=getch();
} /* main */
/* 初始化空栈 * /
/* 输出栈的内容 */
/* 进栈函数 */
/* 出栈函数 */
c代码实现
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20 /* 数组最大界限 */
#include <string.h>
#include <conio.h>
typedef int ElemType; /* 数据元素类型 */
typedef struct
{ ElemType a[MAXSIZE]; /* 一维数组子域 */
int top; /* 栈顶指针子域 */
}SqStack; /* 栈的顺序结构体类型 */
SqStack s1;
void init_s(SqStack *s);
void push(SqStack *s,ElemType e); /* 进栈函数 */
ElemType pop(SqStack *s); /* 出栈函数 */
void out_s(SqStack s); /*输出栈的内容*/
/* 主函数 */
int main()
{
int k;
ElemType e,x;
char ch;
init_s( &s1); /* 初始化一个空栈 */
do { printf("\n\n\n");
printf("\n\n 1. 数据元素e进栈 ");
printf("\n\n 2. 出栈一个元素,返回其值");
printf("\n\n 3. 结束程序运行");
printf("\n======================================");
printf("\n 请输入您的选择 (1,2,3)");
scanf("%d",&k);
switch(k)
{ case 1:{ printf("\n 进栈 e=?"); scanf("%d",&e);
push( &s1,e);
out_s( s1 );
} break;
case 2:{ x= pop( &s1);
printf("\n出栈元素 : %d", x);
out_s( s1 );
} break;
case 3: exit(0);
} /* switch */
printf("\n ----------------");
}while(k>=1 && k<3);
printf("\n 再见!");
printf("\n 打回车键,返回。");
ch=getch();
return 0;
} /* main */
void init_s(SqStack *s){
memset(s->a,0,sizeof(s->a));
s->top=-1;
}
void out_s(SqStack s){
for(int i=0;i<s.top+1;i++){
printf("%d,",s.a[i]);
}
}
void push(SqStack *s,ElemType e){
s->top++;
s->a[s->top]=e;
}
ElemType pop(SqStack *s){
if(s->top!=-1)
return s->a[s->top--];
printf("无元素");
exit(-1); //无元素时退出
}