链式队列

 

#ifndef LINKEDQUEUE_H

#define LINKEDQUEUE_H

 

#include <iostream>

#include <assert.h>

using namespace std;

 

template<class T>

struct LinkNode        //链式队列节点类的定义

{

     T data;  //数据域

     LinkNode<T> *link; //链指针域

     LinkNode(LinkNode<T> *ptr = NULL)    //仅初始化指针成员的构造函数

     {

         link = ptr;

     }

     LinkNode(const T &item,LinkNode<T> *ptr = NULL)    //初始化数据与指针成员的构造函数

     {

         data = item;

         link = ptr;

     }

};

 

template<class T>

class LinkedQueue

{

public:

     LinkedQueue():front(NULL),rear(NULL){}

     ~LinkedQueue()

     {

         MakeEmpty();

     }

     bool EnQueue(const T& x);   //x加入到队列中

     bool DeQueue(T& x);    //删除队头元素,x返回其值

     bool GetFront(T& x)const;   //查看队头元素的值

     void MakeEmpty();  //置空队列

     bool IsEmpty()const

     {

         return (front == NULL) ? true : false;

     }

     int GetSize()const;    //求队列元素个数

     template<class T>

     friend ostream& operator<<(ostream& os,LinkedQueue<T>& q);

private:

     LinkNode<T> *front,*rear;   //队头、队尾指针

};

 

template<class T>

void LinkedQueue<T>::MakeEmpty()

{

     LinkNode<T> *p;

     while(front != NULL)

     {

         p = front;

         front = front->link;

         delete p;

     }

}

 

template<class T>

bool LinkedQueue<T>::EnQueue(const T &x)

{

     if(front == NULL)  //空队列时,新结点成为队列的第一个结点,既是队头又是队尾

     {

         front = rear = new LinkNode<T>(x);

         if(front == NULL)

              return false;

     }

     else //非空队列时,在链尾追加新的结点并更新队尾指针

     {

         rear->link = new LinkNode<T>(x);

         if(rear->link == NULL)

              return false;

         rear = rear->link;

     }

     return true;

}

 

template<class T>

bool LinkedQueue<T>::DeQueue(T &x)

{

     if(IsEmpty() == true)

         return false;

     LinkNode<T> *p = front;

     x = front->data;

     front = front->link;

     delete p;

     return true;

}

 

template<class T>

bool LinkedQueue<T>::GetFront(T &x) const

{

     if(IsEmpty() == true)

         return false;

     x = front->data;

     return true;

}

 

template<class T>

int LinkedQueue<T>::GetSize() const

{

     LinkNode<T> *p = front;

     int count = 0;

     while(p != NULL)

     {

         ++count;

         p = p->link;

     }

     return count;

}

 

template<class T>

ostream& operator<<(ostream& os,LinkedQueue<T>& q)

{

     os<<"队列中元素个数有"<<q.GetSize()<<"个。"<<endl;

     LinkNode<T> *p = q.front;

     int i = 0;

     while(p != NULL)

     {

         os<<++i<<":"<<p->data<<endl;

         p = p->link;

     }

     return os;

}

 

#endif

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值