一.队列的概念与结构
队列:只允许在一端进行插入数据操作, 进行插入操作的一端为队尾,进行删除操作的一端为队头。
二.队列的实现
接下来是队列的实现,包含队列相关功能的实现,并且附带堆队列功能的相关测试。
该程序是用C++完成,相比于C语言,书写明显更加方便简洁。
#include<iostream> using namespace std; #include<assert.h> typedef int QDateType; typedef struct QListNode { struct QListNode* _pNext; QDateType _date; }QNode; class Queue { public: //初始化队列,构造函数 /*Queue() { _front = nullptr; _rear = nullptr; }*/ //创造一个节点,方便之后的连接 QNode* CreatNode() { QNode* tmp = (QNode*)malloc(sizeof(QNode)); if (tmp == nullptr) { printf("malloc failed"); return nullptr; } return tmp; } //队尾入队列 void Push(QDateType date) { if (_front == nullptr) { _rear = CreatNode(); _front = _rear; _front->_date = date; _front->_pNext = nullptr; } else { QNode* tmp = CreatNode(); _rear->_pNext = tmp; _rear = tmp; _rear->_date = date; _rear->_pNext = nullptr; } } //队头出队列 void Pop() { if (_front == nullptr) { return; } _front = _front->_pNext; } //获取对头元素 QDateType Front() { if (_front == nullptr) return 0; return _front->_date; } //获取队尾元素 QDateType Rear() { assert(_front); return _rear->_date; } //返回队列中元素个数 int Size() { int n = 0; QNode* tmp = _front; while (tmp != nullptr) { tmp = tmp->_pNext; n++; } return n; } //检查队列是否为空 int IsEmpty() { if (_front == nullptr) return 0; else return 1; } //将队列打印 void Print() { QNode* tmp = _front; while (tmp != nullptr) { printf("%d->", tmp->_date); tmp = tmp->_pNext; } } //析构函数销毁队列 ~Queue() { free(_front); _front = nullptr; _rear = nullptr; } private: QNode* _front; QNode* _rear; }; void Test1() { Queue q1; q1.Push(1); q1.Push(2); q1.Push(3); q1.Push(4); q1.Push(5); q1.Push(6); q1.Print(); } void Test2() { Queue q1; q1.Push(1); q1.Push(2); q1.Push(3); q1.Push(4); q1.Push(5); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); q1.Print(); } void Test3() { Queue q1; q1.Push(1); q1.Push(2); q1.Push(3); q1.Push(4); q1.Push(5); q1.Push(6); QDateType ret= q1.Front(); printf("%d ", ret); q1.Pop(); QDateType ret1 = q1.Front(); printf("%d ", ret1); q1.Print(); } void Test4() { Queue q1; q1.Push(1); q1.Push(2); q1.Push(3); q1.Push(4); q1.Push(5); q1.Push(6); QDateType ret = q1.Rear(); printf("%d ", ret); q1.Print(); } void Test5() { Queue q1; //q1.Push(1); //q1.Push(2); //q1.Push(3); //q1.Push(4); //q1.Push(5); //q1.Push(6); QDateType ret = q1.Size(); printf("%d ", ret); q1.Print(); } void Test6() { Queue q1; q1.Push(1); q1.Push(2); q1.Push(3); q1.Push(4); q1.Push(5); q1.Push(6); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); q1.Pop(); QDateType ret = q1.IsEmpty(); printf("%d ", ret); q1.Print(); } int main() { //Test1(); //Test2(); //Test3(); //Test4(); //Test5(); //Test6(); return 0; }
三.总结
队列相当于一个特殊的链表,队列有它自己的运用场景。
接下来会是数据结构的二叉树环节。