//数据结构--C++--队列
//队列的定义、插入、删除
#include <iostream>
using namespace std;
class Queue{
private:
int* data;
int head, tail, length;
public:
Queue(int length_input){
//开辟length_input长度的空间
data = new int[length_input];
length = length_input;
//队首标记head
head = 0;
//队尾标记tail
tail = -1;
}
//Queue的析构函数,不同于上面的构造函数】
~Queue(){
//释放空间
delete [] data;
}
//队列的插入函数
void push(int element){
//查看插入位置是否超出队列长度
if(tail + 1 < length){
tail = tail + 1;
//将元素添加到队尾
data[tail] = element;
}
}
//队列的输出函数
void output(){
for(int i = head; i <= tail; i++){
cout<<data[i]<<" ";
}
cout<<endl;
}
//输出队首元素函数
int front(){
//用assert判断队列是否为空,记得头文件加上#include <cassert>
assert(head <= tail);
return data[head];
}
//出队函数
void pop(){
assert(head <= tail);
//把head标记往后移一位就表示删除队首元素
head ++;
}
};
int main() {
//Queue的实例queue,长度为100。
Queue queue(100);
//依次将数据插入队列
for(int i = 1; i<=10;i++){
queue.push(i);
}
queue.output();
//输出队首元素
cout<<queue.front()<<endl;
queue.pop();
queue.output();
return 0;
}
计蒜客 数据结构 Queue
最新推荐文章于 2022-06-26 09:52:45 发布