现在的位置: 首页 > 综合 > 正文

堆栈

2013年04月30日 ⁄ 综合 ⁄ 共 1540字 ⁄ 字号 评论关闭

xcept.h

#pragma once

#include <new.h>

class BadInitializers
{
public:
 BadInitializers() {}
};

class NoMem
{
public:
 NoMem() {}
};

class OutOfBounds
{
public:
 OutOfBounds() {}
};

class SizeMismatch
{
public:
 SizeMismatch() {}
};

class MustBeZero
{
public:
 MustBeZero() {}
};

class BadInput
{
public:
 BadInput() {}
};

 

stack.h

 

#ifndef __Queue_H__
#define __Queue_H__

#include "xcept.h"

template<class T>
class CQueue
{
public:
 CQueue( int MaxQueueSize = 5000 );

 ~CQueue() { delete [] m_pT; }

 bool IsEmpty( void ) const
 {
  return m_nFront == m_nRear;
 }

 bool IsFull( void ) const
 {
  return ( ( ( m_nRear + 1 ) % m_nMaxSize == m_nFront ) ? 1 : 0 );
 }

 T front( void ) const; //返回队首元素

 T back( void ) const; //返回队尾元素

 void push( const T& x );

 void pop( void );

 int size( void ) const { return m_nSize; }
private:
 int m_nFront; //与第一个元素在反时针方向上相差一个位置
 int m_nRear; //指向最后一个元素
 int m_nMaxSize; //队列数组大小
 int m_nSize;
 T* m_pT; //数组
};

template<class T>
void CQueue<T>::pop( void )
{
 if ( IsEmpty() )
 {
  throw OutOfBounds();
 }
 m_nFront = ( m_nFront + 1 ) % m_nMaxSize;
 m_nSize--;
}

template<class T>
void CQueue<T>::push( const T& x )
{
 //把 x 添加到队列的尾部
 //如果队列满,则引发异常 NoMem
 if ( IsFull() )
 {
  throw NoMem();
 }
 m_nRear = ( m_nRear + 1 ) % m_nMaxSize;
 m_pT[ m_nRear ] = x;
 m_nSize++;
}

template<class T>
T CQueue<T>::back( void ) const
{
 if ( IsEmpty() )
 {
  throw OutOfBounds();
 }
 return m_pT[ m_nRear ];
}

template<class T>
T CQueue<T>::front( void ) const
{
 //返回队列的第一个元素
 //如果队列为空,则引发异常 OutOfBounds
 if ( IsEmpty() )
 {
  throw OutOfBounds();  
 }
 return m_pT[ (m_nFront + 1 ) % m_nMaxSize ];
 
}

template<class T>
CQueue<T>::CQueue( int MaxQueueSize /*= 5000000 */ )
{
 //创建一个容量为 MaxQueueSize 的空队列
 m_nMaxSize = MaxQueueSize + 1;
 m_pT = new T[ m_nMaxSize ];
 m_nFront = m_nRear = m_nSize = 0; 
}

#endif

 

抱歉!评论已关闭.