队列的线性实现

继上篇文章 直接贴代码

#include <iostream>
using namespace std;

#define ElemType int
const int INIT_SIZE = 100;
const int INCREMENT_SIZE = 10;
//缺点:浪费空间
class Queue{
private:
int front;
int rear;
int queue_total_size;
ElemType *data;
public:
bool InitQueue(); //构造一个空队列
void DestoryQueue(); //销毁队列
void ClearQueue(); //清空队列
bool QueueEmpty(); //队列是否为空
int QueueLength(); //队列长度
void GetHead(ElemType &e); //获取队头元素
bool EnQueue(ElemType e); //把e插入到队尾
bool DeQueue(ElemType &e); //如果队列不为空,删除队头元素,用e返回其值
};
//初始化队列
bool Queue::InitQueue()
{
this->front = this->rear = 0;
this->data = (ElemType *)malloc(sizeof(ElemType) * INIT_SIZE);
if(!this->data)
return false;
this->queue_total_size = INIT_SIZE;
return true;
}
//销毁队列
void Queue::DestoryQueue()
{
delete this->data;
}
//情况队列
void Queue::ClearQueue()
{
this->rear = this->front;
}
//队列是否为空
bool Queue::QueueEmpty()
{
return this->rear == this->front;
}
//获取队列长度
int Queue::QueueLength()
{
return rear;
}
//获取队头元素
void Queue::GetHead(ElemType &e)
{
e = this->data[front];
}
//进队列
bool Queue::EnQueue(ElemType e)
{
if(this->rear < this->queue_total_size)
{
this->data = (ElemType *)realloc(this->data, sizeof(ElemType) * (this->queue_total_size + INCREMENT_SIZE));
if(!this->data)
return false;
this->queue_total_size += INCREMENT_SIZE;
}
this->data[rear++] = e;
return true;
}
//出队列
bool Queue::DeQueue(ElemType &e)
{
e = this->data[front];
front++;
return true;
}
int main()
{
int e;
Queue queue;
queue.InitQueue();
queue.EnQueue(3);
queue.EnQueue(4);
queue.EnQueue(5);
queue.DeQueue(e);
cout<<e;
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值