C++模板类+嵌套类实例

C语言 专栏收录该内容
6 篇文章 0 订阅

queue.h

#ifndef QUEUE_H_

#define QUEUE_H_

template<class Type>
class Queue{
private:
    enum {Q_SIZE = 10};
    class Node{
    public:
        Type data;
        Node * next;
        Node(const Type data) : data(data), next(0) {}
    };  
    Node *front;
    Node *rear;
    int curSize;
    int maxSize;
public:
    Queue(int size = Q_SIZE);
    ~Queue();
    bool isFull() const;
    bool isEmpty() const ;
    bool enQueue(const Type data);
    bool deQueue();
    void tarverseQueue() const;
};

#endif


queue.cpp

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <valarray>
#include "queue.h"
using std::cout;
using std::endl;

template<class Type>
Queue<Type>::Queue(int size) : maxSize(size) {
    front = rear = 0;
    curSize = 0;
}

template<class Type>
Queue<Type>::~Queue() {
    Node *tmp;
    while (front != 0) {
        tmp = front;
        front = front->next;
        delete tmp;
    }
}

template<class Type>
bool Queue<Type>::isFull() const {
    return curSize >= maxSize;
}

template<class Type>
bool Queue<Type>::isEmpty() const {
    return curSize == 0;
}

template<class Type>
bool Queue<Type>::enQueue(const Type data) {
    if (isFull()) {
        return false;
    }   
    Node *node = new Node(data);
    if (front == 0) {
        front = node;
    } else {
        rear->next = node;
    }   
    rear = node;
    curSize++;
    return true;
}

template<class Type>
bool Queue<Type>::deQueue() {
    if (isEmpty()) {
        return false;
    }
    Node *tmpNode = front;
    front = front->next;
    delete tmpNode;
    if (front == 0) {
        rear = 0;
    }
    curSize--;
    return true;
}

template<class Type>
void Queue<Type>::tarverseQueue() const {
    Node *head = front;
    while (head != 0) {
        cout << head->data << endl;
        head = head->next;
    }
}

int main(int argc, char *argv[]) {
    Queue<int> queue(10);
    queue.enQueue(11);
    queue.enQueue(12);
    queue.tarverseQueue();
    return 0;
}



  • 1
    点赞
  • 2
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值