日常说明:首先博主也是菜鸟一枚,有错误欢迎大家指正。另外本博客所有的代码博主编写后均调试
通过。重要提醒!!!!博主使用的是VS2017,如果有低版本的小伙伴
最好新建空项目将此代码复制上去。
更多算法请关注我的算法专栏https://blog.csdn.net/column/details/20417.html
运行截图:
SqQueue.h
#pragma once
/**********************************
* algorithms.h :队列的基本操作 *
* author : shilei *
* created : 2018.3.24 *
***********************************/
#include<iostream>
#include<cstdlib>
#include"malloc.h"
#include"corecrt_malloc.h"
#include<exception>
using namespace std;
#define QueueSize 20//最初队列的容量
#define QUE_INCREAMENT 10
#define QElemtype char
class SqQueue
{
public:
SqQueue();
~SqQueue();
void EnQueue(QElemtype e);
QElemtype DeQueue();
int Getlength();
QElemtype GetElem(int n);
private:
QElemtype * elem;
int front;
int rear;
int length;//当前数据元素的个数
int queue_size;//当前队列的容量
};
SqQueue::SqQueue()
{
this->elem = (QElemtype*)malloc(QueueSize * sizeof(QElemtype));
this->front = this->rear = 0;
this->length = (this->rear - this->front + QueueSize) % QueueSize;
int queue_size = QueueSize;
}
SqQueue::~SqQueue()
{
this->front = this->rear = 0;
delete[]elem;
}
int SqQueue::Getlength()
{
/*this->length = (this->rear - this->front + QueueSize) % QueueSize;*/
return this->length;
}
void SqQueue::EnQueue(QElemtype e)
{
if ((this->rear+1)%QueueSize == this->front)//若队列满,则扩容
{
this->elem = (QElemtype*)realloc(this->elem,(QueueSize + QUE_INCREAMENT)*sizeof(QElemtype));
this->queue_size = QueueSize + QUE_INCREAMENT;
}
this->elem[this->rear] = e;
this->rear = (rear + 1) % QueueSize;
this->length++;
}
QElemtype SqQueue::DeQueue()
{
if (this->rear == this->front)//空队列
{
throw out_of_range("队列为空,不能进行出队操作");
}
QElemtype e = this->elem[this->front];
this->front = (this->front + 1) % QueueSize;
return e;
}
QElemtype SqQueue::GetElem(int n)
{
if (this->rear == this->front)
{
throw logic_error("空队列,无法获取数据元素");
}
if (n < this->Getlength())
{
return this->elem[this->front + n ];
}
throw out_of_range("n超出队列数据的长度");
}
SqQueue.cpp
#include"SqQueue.h"
/**********************************
* algorithms.cpp :队列的基本操作与进制转换 *
* author : shilei *
* created : 2018.3.24 *
***********************************/
void D_to_H()
{
char H[16] = { '0','1','2','3','4','5','6','7','8','9','A', 'B', 'C','D','E','F' };
SqQueue queue;
int n;
cout << endl;
cout << endl;
cout<<"*********十进制转换十六进制*********"<<endl;
cout << endl;
cout << "请输入十进制数字:";
cin >> n;
cout << endl;
cout << endl;
cout << "十进制数字" << n << "转换为十六进制结果为:";
while (n)
{
int i = 0;
int e = n % 16;
queue.EnQueue(H[e]);
n = n/16;
i++;
}
for (int i = queue.Getlength(); i > 0; i--)
{
cout<<queue.GetElem(i-1);
}
}
int main()
{
D_to_H();
cout << endl;
cout << endl;
cout << "恭喜你!!!!转换完成,";
return 0;
}