C++类模板实现链队

/*定义链队*/

template <class T>
class LinkQueue {
    public:
      linkQueue();    //构造函数
      bool isEmpty();    //判空函数
      void enQueue(const T&);    //进队函数
      T deQueue();    //出队函数
      T getHead();    //返回对头元素
      ~linkQueue();    //析构函数
    private:
      //定义结点
      struct node {
          T data;    //结点中保存的数据
          node* next;    //后继指针
          node():next(NULL){};    //构造函数,无参数
          node(const T& x, node* n = NULL):data(x), next(n){};    //构造函数,带参数
          ~node(){};
      };
      node* head;    //队头指针
      node* tail;    //队尾指针
};

//构造函数
template <class T>
LinkQueue<T>::linkQueue() {
    head = tail = NULL;
}

//判空函数
template <class T>
bool LinkQueue<T>::isEmpty() {
    return head == NULL;
}

//进队函数
template <class T>
void LinkQueue<T>::enQueue(const T& x) {
    node* add = new node(x);
    if (head) {
        tail->next = add;
        tail = add;
    } else {
        head = tail = add;
    }
}

//出队函数
template <class T>
T LinkQueue<T>::deQueue() {
    if (isEmpty()) {
        throw 1;
    }
    
    T d = head->data;
    node* tmp = head;
    head = head->next;
    delete tmp;
    return d;
}

//返回对头元素
template <class T>
T LinkQueue<T>::getHead() {
    if (isEmpty()) {
        throw 1;
    }

    return head->data;
}

//析构函数
template <class T>
LinkQueue<T>::~linkQueue() {
    while (head != NULL) {
        node* tmp = head;
        head = head->next;
        delete tmp;
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值