《数据结构》实验报告
实验序号:4 实验项目名称:栈的操作 学 号 实验地点 实1#514 姓 名 指导教师 林仙丽 专业、班 实验时间 2013-12-06 一、实验目的及要求 1. 熟悉栈的基本概念; 2. 掌握栈的顺序存储结构; 3.掌握栈的应用。 二、实验设备(环境)及要求 微型计算机; windows 操作系统; Microsoft Visual Studio 6.0集成开发环境。 三、实验内容与步骤 1.栈的顺序表表示和实现的如下: #include #define MaxSize 100 using namespace std; typedef int ElemType; typedef struct { ElemType data[MaxSize]; int top; }SqStack; void InitStack(SqStack *st) //初始化栈 { st->top=-1; } int StackEmpty(SqStack *st) //判断栈为空 { return (st->top==-1); } void Push(SqStack *st,ElemType x) //元素进栈 { if(st->top==MaxSize-1) { printf(\栈上溢出!\\n\ } else { st->top++; //移动栈顶位置 st->data[st->top]=x; //元素进栈 } } void Pop(SqStack *st,ElemType &e) //出栈 { if(st->top==-1) { printf(\栈下溢出\\n\ } else { e=st->data[st->top]; //元素出栈 st->top--; //移动栈顶位置 } } int main() { SqStack L; SqStack *st=&L; ElemType e; int i; InitStack(st); for(i=1;i<10;++i) { Push(st,i); printf(\入栈元素是:%d\\n\ } for(i=1;i<10;++i) { Pop(st,e); printf(\出栈元素是:%d\\n\ } return 0; } 改写以上程序,实现功能如下: 改写Push和Pop函数,使得以上两个函数可以一次性将一个数组入栈和出栈。 2.C/C++的库函数中已经实现了栈,实例如下: #include //引入栈 using namespace std; int main() { int a; stacks; scanf(\ s.push(a); //入栈 printf(\取得栈顶元素输出 s.pop(); //出栈 return 0; } 请根据以上程序,设计算法如下(任选一题): 1.判别一个算术表达式中的圆括号配对是否正确。 运行结果截图: 2.判别一个算术表达式中的圆括号和方括号配对是否正确。 运行结果截图: 四、分析与讨论 因为有了上一章的练习,使得栈做起来相对容易。 对上机实践结果进行分析,上机的心得体会。 五、教师评语 签名: 日期: 附源程序清单: 1.
#include #include #include #define MaxSize 100 using namespace std; typedef int ElemType; typedef struct { ElemType data[MaxSize]; int top; }SqStack;
void InitStack(SqStack *st) //初始化栈 { st->top=-1; }
int StackEmpty(SqStack *st) //判断栈为空 { return (st->top==-1); }
void Push(SqStack *st,ElemType x) //元素进栈 { if(st->top==MaxSize-1) { printf(\栈上溢出!\\n\ } else { st->top++; //移动栈顶位置
成绩