数据结构之队列

队列(queue)是一种线性结构,定义如下:若给定队列Q=(a0,a1,…,an-1),则称a0是队头元素,an-1是队尾元素。元素a0,…,an-1依次入队,出队的顺序与入队相同,a0出队后,a1才能出队,因此又称队列为先进先出(FirstIn First Out——FIFO)的动态线性数据结构出队列只能在队头,入队列只能在队尾

队列的表示方法有顺序表示、循环表示和链式表示。

顺序表示如图头指针f指向队首元素的前一个位置,尾指针r指向最后一个元素。从图中可以看出,若再有元素入队,将发生溢出,而其实队列中还有3个空元素空间,我们称这种情况为假溢出。

为解决这种假溢出的情况,我们把数组逻辑上堪称呢个一个头尾相连的环。如下图.下图为关于循环队列的操作,由图可以总结出来一些规律:入队列时,(rear+1)%MaxSize;出队列时,(front+1)%MaxSize;空队列即front==rear;满队列即(rear+1)%MaxSize==front;满队列实际上仍有一个元素空间没被利用。

顺序表示的队列的描述:

template <class T>
class SeqQueue:public Queue<T>
{ public:
    SeqQueue(int mSize);
    ~SeqQueue(){ delete []q;}
    bool IsEmpty() const;      
    bool IsFull() const;
    bool Front(T& x)const;
    bool EnQueue(T x);
    bool DeQueue();
    void Clear(){front=rear=0;}
  private:
    int front,rear;
    int maxSize;
    T *q;
};
构造函数
template <class T>
SeqQueue<T>::SeqQueue(int mSize)
{ //生成一个空队列
    maxSize=mSize;
    q=new T[maxSize];
    front=rear=0;
}

析构函数
~SeqQueue()
{ 
    delete []q;
}
判断是否为空队列
template <class T>
bool SeqQueue<T>::IsEmpty() const
{ 
   return front==rear;
}
判断是否为满队列
template <class T>
bool SeqQueue<T>::IsFull() const
{ 
   return (rear+1) % maxSize==front;  
}
取队列元素
template <class T>
bool SeqQueue<T>::Front(T& x)
{ 
  if(IsEmpty()) {
     cout<<"empty"<<endl;
     return false;
   }
   x=q[(front+1) % maxSize];
   return true;
}
入队列
template <class T>
bool SeqQueue<T>::EnQueue(T x)
{ 
    if(IsFull()) {  
          cout<<"Full"<<endl;
          return false;
     }
     q[(rear=(rear+1) % maxSize)]=x;
     return true;
}
出队列
template <class T>
bool SeqQueue<T>::DeQueue()
{ 
  if(IsEmpty()) {
      cout<<"Underflow"<<endl;
       return false;
  }
  front=(front+1) % maxSize;
  return true;
 }

链式表示的队列如图 .链式队列的入队和出队操作

入队列
EnQueue(T x){
<span style="white-space:pre">	</span>Node<T> *q = new Node<T>;
<span style="white-space:pre">	</span>q->element = x;
<span style="white-space:pre">	</span>q->link = NULL;
<span style="white-space:pre">	</span>rear->link = q;
<span style="white-space:pre">	</span>rear=q;
}
出队列
DeQueue(){
<span style="white-space:pre">	</span>Node<T> *q = front;
<span style="white-space:pre">	</span>front=front->link;
<span style="white-space:pre">	</span>del q;
}
队列作为一种重要的数据结构,是必须要掌握的。我们在实际编程或者阅读开源项目时,会遇到很多关于队列的应用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值