正在加载图片...
栈的删除函数 template<class Type> Type Stack<Type>: Remove(i if( Is Empty()) Empry (; return NULL; J Type& x=elements[topr- return &x 队列的类定义(继承Bqg类) template<class Type> class Queue publie Bag i Queue( int s== DefaulISice ) ∥构造函数 Queue (; 斤构函数 }; 队列的构造函数 template<class Type> Queue<Type> Queue( int s= ): Bag(s5)0 /队列的构造函数 Queue将调用Bag的构造函数 优先级队列的类定义(继承Bqg类 template <class Type> class PQueue public Bag i public PQueue( int s== DefaulSize ) ∥构造函数 PQueue( 析构函数 Type"PQRemone ( 删除函数 优先级队列的构造函数 template <class Type> PQueue<Type>:: PQueue int s:): Bag(s2)0 ∥建立一个最大具有s个元素的空优先级队列。lop=-1。 优先级队列的删除函数 template <class Type> Type "PQueue<type>: Remove(i ∥若优先级队列不空则函数返回该队列具最大优先权(值最小)元素的值,同时将该元素删除 if( Is Empry()) Empry ( return NULL; J Type& ∥假设 elements[0]是最小值,继续找最小值 for int i=1: i<= top: 1++) if elementsa <min)i min=elements; minindex =i;) ∥用最后一个元素填补要取走的最小值元素 return& mi ∥返回最小元素的值 4-15试利用优先级队列实现栈和队 【解答】 template <class Type> class PQueue; 前视的类定义 template <class Type> class PQueuenode t ∥优先级队列结点类的定义 friend class PQueue<Type> ∥ PQueue类作为友元类定义栈的删除函数 template<class Type> Type * Stack<Type> :: Remove ( ) { if ( IsEmpty ( ) ) { Empty ( ); return NULL; } Type& x = elements [ top-- ]; return &x; } 队列的类定义(继承 Bag 类) template<class Type> class Queue : public Bag { public: Queue ( int sz = DefaultSize ); //构造函数 ~Queue ( ); //析构函数 }; 队列的构造函数 template<class Type> Queue<Type> :: Queue ( int sz ) : Bag ( sz ) { } //队列的构造函数 Queue 将调用 Bag 的构造函数 优先级队列的类定义(继承 Bag 类) template <class Type> class PQueue : public Bag { public: PQueue ( int sz = DefaultSize ); //构造函数 ~PQueue ( ) { } //析构函数 Type *PQRemove ( ); //删除函数 } 优先级队列的构造函数 template <class Type> PQueue<Type> :: PQueue ( int sz ) : Bag ( sz ) { } //建立一个最大具有 sz 个元素的空优先级队列。top = -1。 优先级队列的删除函数 template <class Type> Type *PQueue<Type> :: Remove ( ) { //若优先级队列不空则函数返回该队列具最大优先权(值最小)元素的值, 同时将该元素删除。 if ( IsEmpty ( ) ) { Empty ( ); return NULL; } Type& min = elements[0]; //假设 elements[0]是最小值,继续找最小值 int minindex = 0; for ( int i = 1; i <= top; i++ ) if ( elements[i] < min ) { min = elements[i]; minindex = i; } elements[minindex] = elements[top]; //用最后一个元素填补要取走的最小值元素 top--; return& min; //返回最小元素的值 } 4-15 试利用优先级队列实现栈和队列。 【解答】 template <class Type> class PQueue; //前视的类定义 template <class Type> class PQueueNode { //优先级队列结点类的定义 friend class PQueue<Type>; //PQueue 类作为友元类定义
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有