您的位置:首页 > 产品设计 > UI/UE

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

2018-01-19 23:38 477 查看
在学习模板方法的时候,我刚好在看数据结构。想着能不能通过模板方法实现一个通用的
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: 这段代码,我本人比较满意。~

以上。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: