队列
- 引言
- 示例
- 开发环境
- 运行结果
引言
队列先进先出,队头出队,队尾入队,其存储可以分为顺序存储和链式储存。本文记录队列的顺序存储。也就是队列中的元素存储的内存空间是连续的,这里使用数组来模拟线性队列。
示例
直接上代码:
SeqQueue.h
#pragma once/**/
#define MAX_SIZE 1024
typedef struct SEQQUEUE {void* data[MAX_SIZE];int size;
}SeqQueue;class MySeqQueue
{
public:MySeqQueue();~MySeqQueue();void pushSeqQueue(void * data);void popSeqQueue();void* getFrontSeqQueue();void* getBackSeqQueue();int getSizeSeqQueue();void clearSeqQueue();
private:SeqQueue *m_queue;
};
SeqQueue.cpp
#include "SeqQueue.h"MySeqQueue::MySeqQueue()
{m_queue = new SeqQueue();m_queue->size = 0;for (int i = 0; i < MAX_SIZE;++i){m_queue->data[i] = nullptr;}
}MySeqQueue::~MySeqQueue()
{if (m_queue != nullptr){delete m_queue;m_queue = nullptr;}
}void MySeqQueue::pushSeqQueue(void * data)
{if (m_queue == nullptr){return;}if (data == nullptr) {return;}m_queue->data[m_queue->size] = data;m_queue->size++;
}void MySeqQueue::popSeqQueue()
{if (m_queue == nullptr){return ;}if (m_queue->size == 0) {return;}void * fontData = m_queue->data[0];for (int i = 1; i < m_queue->size; ++i){m_queue->data[i - 1] = m_queue->data[i];}m_queue->size--;
}void * MySeqQueue::getFrontSeqQueue()
{if (m_queue == nullptr){return nullptr;}if (m_queue->size == 0){return nullptr;}return m_queue->data[0];
}void * MySeqQueue::getBackSeqQueue()
{if (m_queue == nullptr){return nullptr;}if (m_queue->size == 0){return nullptr;}return m_queue->data[m_queue->size-1];
}int MySeqQueue::getSizeSeqQueue()
{if (m_queue == nullptr){return -1;}return m_queue->size;
}void MySeqQueue::clearSeqQueue()
{if (m_queue == nullptr){return ;}for (int i = 0; i < MAX_SIZE; ++i){m_queue->data[i] = nullptr;}m_queue->size = 0;
}
main.cpp
#include <iostream>
#include "SeqQueue.h"using namespace std;typedef struct PERSON {char name[64];int age;
}Person;void print(Person *data)
{cout << "name;" << data->name << " age:" << data->age << endl;
}
void test()
{MySeqQueue * queque = new MySeqQueue;Person p1 = {"sahus",34};Person p2 = {"护士",67};Person p3 = {"的防护",56};Person p4 = {"rjhuhxd",4};queque->pushSeqQueue(&p1);queque->pushSeqQueue(&p2);queque->pushSeqQueue(&p3);queque->pushSeqQueue(&p4);cout <<"size: "<<queque->getSizeSeqQueue()<<endl;cout << "front: " <<endl;Person *data = (Person*)queque->getFrontSeqQueue();print(data);cout << "back: " <<endl;Person *backData = (Person *)queque->getBackSeqQueue();print(backData);cout << "============元素出队================== " << endl;while (queque->getSizeSeqQueue() != 0){Person *data = (Person*)queque->getFrontSeqQueue();print(data);queque->popSeqQueue();}delete queque;queque = nullptr;
}int main()
{test();return 0;
}// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单// 入门使用技巧:
// 1. 使用解决方案资源管理器窗口添加/管理文件
// 2. 使用团队资源管理器窗口连接到源代码管理
// 3. 使用输出窗口查看生成输出和其他消息
// 4. 使用错误列表窗口查看错误
// 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目
// 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
开发环境
vs2017控制台输出程序。