实验四:顺序栈和链栈

来源:互联网 发布:怎样让淘宝号有心 编辑:程序博客网 时间:2024/05/21 10:01

一、实验目的

熟练掌栈和队列的结构特点,掌握栈和队列的顺序存储和链式存储结构和实现。

二、实验过程

1.顺序栈
#ifndef SeqStack_H#define SeqStack_Hconst int StackSize=10;templateclass SeqStack{public:SeqStack();~SeqStack(){}void Push(DataType x);  //x入栈DataType Pop();   //将栈顶元素弹出DataType GetTop();  //取栈顶元素int Empty();  //判断栈是否为空private:DataType data[StackSize];  //存放栈元素的数组int top;                   //栈顶指针,指示栈顶元素在数组中的下标};#endif#include"SeqStack.h"templateSeqStack::SeqStack(){top=-1;}templatevoid SeqStack::Push(DataType x){if(top==StackSize-1)throw"上溢";top++;data[top]=x;}templateDataType SeqStack::Pop(){DataType x;if(top==-1)throw"下溢";x=data[top--];return x;}templateDataType SeqStack::GetTop(){if(top!=-1)return data[top];}templateint SeqStack::Empty(){if(top==-1)return 1;else return 0;}#includeusing namespace std;            //引入输入输出流#include"SeqStack.cpp"           //引入类SeqStack的成员函数定义void main()                   //主函数{SeqStackS;            //创建模板类的实例if(S.Empty())cout<<"栈为空"<



2.链栈

#ifndef LinkStack_H#define LinkStack_Htemplatestruct Node{DataType data;Node * next;};templateclass LinkStack{public:LinkStack();~LinkStack();void Push(DataType x);DataType Pop();DataType GetTop();int Empty();private:Node*top;};#endif;#include"LinkStack.h"templateLinkStack::LinkStack(){top=NULL;}templateLinkStack::~LinkStack(){Node*q=NULL;while(top!=NULL){q=top;delete q;}}templatevoid LinkStack::Push(DataType x){Node *s=NULL;s=new Node;s->data=x;s->next=top;top=s;}templateDataType LinkStack::Pop(){Node *p=NULL;if(top==NULL)throw"下溢";int x;x=top->data;p=top;top=top->next;delete p;return x;}templateDataType LinkStack::GetTop(){if(top!=NULL)return top->data;}templateint LinkStack::Empty(){if(top==NULL)return 1;else return 0;}#includeusing namespace std;#include"1.cpp"void main(){LinkStackS;if(S.Empty())cout<<"Link is Enpty"<


三、实验心得

按照书上的部分算法提示,和实验书的源程序,可以写出栈链的程序,书本的理论知识很详细,通过实验可以将他实现。通过实验,可以更对顺序栈和链栈之间的区别更加清晰。


原创粉丝点击