正在加载图片...
virtual int IsFull(i return top== maxsie-1; ∥判满函数 virtual void Empty()i cout <<"Data Structure is empty: "< endl; j virtual void Full(i cerr <<"DataStructure is fill. < endl;) ∥储数组 Int marsie 数组的大小 int top; 数组当前元素个数 Bag类的构造函数 template<class Type> Bag<Type> :: Bag( int MaxBag Size ) MaxSie( MarBag Size )i elements new Type MaxIe Bag类的析构函数 template<class Type> Bag<Type>: :-Bag (i delete elements Bag类的插入函数 template<class Type> void Bag<Type>: Add( const Type item )4 if( Is Full()Full (; else elements [++top]=item; Bag类的删除函数 template <class Type> Type*Bag<Type>: Remove(& if( lsEmpry()) Empry ( return NULL; Type& x=elements ∥保存被删除元素的值 for int i=0; i< top; i++) ∥后面元素填补上来 return &x: 栈的类定义(继承Bg类) template<class Type> class Stack: public Bag i public: Stack( int s== DefaulISie ) ∥构造函数 -Stack(; 析构函数 Type Remore (; ∥删除函数 栈的构造函数 template<class Type> Stack<Type> : Stack( int s=): Bag(s:)0 栈的构造函数Sack将调用Bag的构造函数 栈的析构函数 template<class Type> Stack<Type>: -Stack(3 ∥栈的析构函数将自动调用Bag的析构函数,以确保数组 elements的释放virtual int IsFull ( ) { return top == maxSize - 1; } //判满函数 private: virtual void Empty ( ) { cout << “Data Structure is empty.” << endl; } virtual void Full ( ) { cerr << “DataStructure is full.” << endl; } Type *elements; //存储数组 int maxSize; //数组的大小 int top; //数组当前元素个数 }; Bag 类的构造函数 template<class Type> Bag<Type> :: Bag ( int MaxBagSize ) : MaxSize ( MaxBagSize ) { elements = new Type [ MaxSize ]; top = -1; } Bag 类的析构函数 template<class Type> Bag<Type> :: ~Bag ( ) { delete [ ] elements; } Bag 类的插入函数 template<class Type> void Bag<Type> :: Add ( const Type & item ) { if ( IsFull ( ) ) Full ( ); else elements [ ++top ] = item; } Bag 类的删除函数 template <class Type> Type *Bag<Type> :: Remove ( ) { if ( IsEmpty ( ) ) { Empty ( ); return NULL; } Type & x = elements [0]; //保存被删除元素的值 for ( int i = 0; i < top; i++ ) //后面元素填补上来 elements [i] = elements [ i+1]; top--; return &x; } 栈的类定义(继承 Bag 类) template<class Type> class Stack : public Bag { public: Stack ( int sz = DefaultSize ); //构造函数 ~Stack ( ); //析构函数 Type *Remove ( ); //删除函数 }; 栈的构造函数 template<class Type> Stack<Type> :: Stack ( int sz ) : Bag ( sz ) { } //栈的构造函数 Stack 将调用 Bag 的构造函数 栈的析构函数 template<class Type> Stack<Type> :: ~Stack ( ) { } //栈的析构函数将自动调用 Bag 的析构函数, 以确保数组 elements 的释放
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有