顺序栈实现

来源:互联网 发布:js获取input file的流 编辑:程序博客网 时间:2024/06/04 22:46

一、实验目的

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

2、学会使用栈解决实际问题。

二、实验内容

1、自己确定结点的具体数据类型和问题规模:

分别建立一个顺序栈和链栈,实现栈的压栈和出栈操作。

三、源代码

#include<iostream>using namespace std;const int StackSize=20;template<typename T>class SeqStack{private:T data[StackSize];//存放栈元素的数组int top;//栈顶指针public:SeqStack(){top=-1;}//构造函数~SeqStack(){}//析构函数int Length();//栈的长度void Push(T x);//入栈T Pop();//出栈T GetTop(){if(top!=-1) return data[top];}//取栈顶元素void Empty();//判断栈是否为空};template<class T>void SeqStack<T>::Push(T x){if(top==StackSize-1) throw"上溢";data[++top]=x;//top指向的位置即为元素x入栈的位置}template<class T>int SeqStack<T>::Length(){if(top==-1) return 0;else return top+1;}template<class T>T SeqStack<T>::Pop(){if(top==-1) throw"下溢";T x=data[top--];return x;}template<class T>void SeqStack<T>::Empty(){if(top==-1)cout<<"1";elsecout<<"0";}void main(){SeqStack<int>b;cout<<"判断栈是否为空,若空则1,否为0:";b.Empty();cout<<endl;b.Push(1);b.Push(2);b.Push(3);b.Push(4);b.Push(5);cout<<"元素1,2,3,4,5入栈后栈的长度为:"<<b.Length()<<endl;cout<<"取栈顶元素:"<<b.GetTop()<<endl;cout<<endl;cout<<"栈顶出栈"<<endl;b.Pop();cout<<"取栈顶元素:"<<b.GetTop()<<endl;cout<<"栈的长度为:"<<b.Length()<<endl;}

四、运行结果



五、实验心得
通过实验,大概了解了栈的栈的顺序存储的实现。对比之前写的线性表,相对而言简单一些。

原创粉丝点击