cpp: 使用类模板以及链表实现队列Queue

  • 在学习模板方法的时候,我刚好在看数据结构。想着能不能通过模板方法实现一个通用的queue & stack & list呢?
  • 当时尝试了,但是失败了。因为当时不知道这需要使用到类模板。
    ps: 如果不是基于oop去实现的,模板方法肯定是够用的;但是既然是cpp代码,我还是倾向于使用oop的思想去实现。毕竟相对更容易处理,而且代码也更清晰。

  • 现在,贴一下我的代码,以作纪念。
    ps:关于通过链表实现:主要是思路清晰就好了,实现起来就很容易;如果写的时候,思路不清晰,只能去用数组了,或者等思路清晰的时候再去写~

  • 首先是模板类queue的代码

//
// Created by cat on 2018/1/19.
//

#ifndef CPP02_QUEUE_H
#define CPP02_QUEUE_H

/**
 * 通过 模板类实现 队列 (内部使用链表实现)
 * 队列(FIFO) --> 先进先出
 * @tparam V
 */
template<typename V>
class Queue {

private:
    struct Node {
        Node *next;
        V data;
    };

    unsigned int max;
    int length; // 实际上可以不需要这个变量
    Node *front; // 头指针
    Node *rear; // 尾指针

public:
    Queue(unsigned int max)
            : max(max), front(nullptr), rear(nullptr) {
        this->length = 0;
    }

    virtual ~Queue() {
        while (this->front) {
            this->pop();
        }
    }

    unsigned long size() const { return isEmpty() ? 0 : 1 + this->rear - this->front; }

    bool isFull() const;

    bool isEmpty() const { return this->front == nullptr; }

    /**
     *  add a data 2 queue
     * @param data
     * @return true if push ok ,else false
     */
    bool push(const V &data);

    /**
     * pop the first from the queue
     * @return true if pop ok, else false
     */
    bool pop();

};

template<typename V>
bool Queue<V>::isFull() const {
    if (isEmpty() && this->max == 0) return true;
    return (this->rear - this->front) == this->max;
}

template<typename V>
bool Queue<V>::push(const V &data) {
    if (isFull()) {
        // has no room 2 place the newly data 
        return false;
    }
    Node *node = new Node;
    node->next = nullptr;
    node->data = data;
    if (isEmpty()) {
        this->front = node;
        this->rear = node;
    } else {
        // add to the last
        this->rear->next = node;
        this->rear = node;
    }
    this->length += 1;
    return true;
}

template<typename V>
bool Queue<V>::pop() {
    if (isEmpty()) {
        return false;
    }

    if (this->front == this->rear) {
        delete this->front;
        this->front = this->rear = nullptr;
    } else {
        Node *drop = this->front;
        this->front = drop->next;
        delete drop;
    }
    this->length -= 1;
    return false;
}


#endif //CPP02_QUEUE_H

这段代码就已经完全实现了Queqe模板

  • 然后是验证的代码:
#include <iostream>
#include "Queue.h"
#include <string>

using namespace std;

int main() {

    Queue<string> list(12);

    list.push("duck");
    list.push("fuck");
    list.push("you");

    cout << "list.size()==" << list.size() << endl;

    list.pop();
    cout << "list.size()==" << list.size() << endl;
    return 0;
}

虽然看验证代码看不出什么效果,不过我保证,没有任何的内存泄露。想看里面的细节,建议debug单步查看内部的数据变化。~

ps: 这段代码,我本人比较满意。~

以上。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值