数据结构实验报告-栈和队列.doc

本章共18个实验题目。 一、顺序栈的建立 1.定义顺序栈的存储结构 2.初始化顺序栈为空栈(InitStack_Sq) 3.输入要入栈的元素个数n 4.向顺序栈中压入n个元素(Push_Sq) 5.将顺序栈中的元素从栈顶到栈底依次输出(StackTraverse_Sq) 6.销毁顺序栈(DestroyStack_Sq) 例如: 5 4 3 5 10 9 9 10 5 3 4 //遍历输出时最后一个元素后有一个空格 程序: #includeiostream using namespace std; typedef struct { int *base; int *top; int stacksize; }SqStack; void InitStack_Sq(SqStack S) { S.base=new int[100]; S.top=S.base; S.stacksize=100; } void Push_Sq(SqStack S,int e) { *S.top++=e; } void Pop(SqStack S,int e) { e=*--S.top; } void StackTraverse_Sq(SqStack S,int n) { int e; int m=n; while(m--) { Pop(S,e); coute ; } } void DestroyStack_Sq(SqStack S) { S.base=NULL; S.top=S.base; } int main() { SqStack S; InitStack_Sq(S); int n,i; int e; cinn; int a[n]; for(i=0;in;i++) { cina[i]; } for(i=0;in;i++) { Push_Sq(S,a[i]); } StackTraverse_Sq(S,n); } 二、顺序栈的入栈 1.定义顺序栈入栈函数(Push_Sq) 2.输入要入栈的元素个数n 3.向顺序栈中压入n个元素 4.将顺序栈中的元素从栈底到栈顶依次输出(StackTraverse_Sq) 5.销毁顺序栈(DestroyStack_Sq) 例如: 5 6 2 8 10 9 9 10 8 2 6 //遍历输出时最后一个元素后有一个空格 程序: #include iostream #include stdlib.h using namespace std; #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef int SElemType; #define MAXSIZE 100 typedef struct { SElemType *base; SElemType *top; int stacksize; }SqStack; Status InitStack_Sq(SqStack S) { S.base=new SElemType[MAXSIZE]; if(!S.base) exit(OVERFLOW); S.top=S.base; S.stacksize=MAXSIZE; return OK; } void DestroyStack_Sq(SqStack S) { if(S.base) delete []S.base; S.top=S.base=NULL; } //在此处定义入栈函数Push_Sq void Push_Sq(SqStack S,SElemType e) { *S.top++=e; } void StackTraverse_Sq(SqStack S) { SElemType *p; p=S.top; while(p!=S.base) { cout*--p ; } coutendl; } int main() { SqStack S; InitStack_Sq(S); int n; SElemType e; cinn; for(int i=1;i=n;i++) { cine; Push_Sq(S,e); //此处调用入栈函数 } StackTraverse_Sq(S); DestroyStack_Sq(S); return

文档评论(0)

1亿VIP精品文档

相关文档