数据结构|顺序栈的实现(实验3.1)

来源:互联网 发布:网络骑士是哪里人 编辑:程序博客网 时间:2024/06/05 02:18

一、实验目的

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

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

二、实验内容

1、自己确定结点的具体数据类型和问题规模,建立一个顺序栈,实现栈的压栈和出栈操作。


源代码如下:

#include<iostream>  using namespace std;  const int StackSize = 10;  template<class T>  class SeqStack{    public:          SeqStack(){  top=-1; };        ~SeqStack(){}        void push(T x);         T pop();//T gettop();        int empty();//void print();    private:          T data[StackSize]; //           int top;  // }; template<class T>  void SeqStack<T>::push(T x)  {      if (top==StackSize-1) throw("上溢");     top++;   data[top]=x;}  template<class T>  T SeqStack<T>::pop()               {  T x;   if (top==-1)throw("下溢");   x=data[top--];   return x;}      template<class T>      T SeqStack<T>::gettop( )    {    if(top!=-1)return data[top];}    template<class T>      int SeqStack<T>::empty( )  {       if(top==-1)         return 1;  else return 0;     }   template< class T >  void SeqStack<T>::print()  {      for( int i=0 ; i<=top ; i++)      {  cout<<data[i]<<" ";}      cout<<endl;  }   void main()    {  SeqStack<int>S;if(S.empty())cout <<"栈为空"<<endl;else cout<<"栈非空"<<endl;cout<<"对5和10,15进行入栈操作"<<endl;S.push(5);S.push(10);S.push(15);cout<<"结果如下:"<<endl;S.print();cout<<"栈顶元素为:"<<endl;cout<<S.gettop()<<endl;cout<<"执行出栈操作"<<endl;S.pop();cout<<"栈顶元素为:"<<endl;cout<<S.gettop()<<endl;cout<<"结果如下:"<<endl;S.print();} 
运行结果如下:


阅读全文
0 0