C++数据结构--循环队列的实现

╰+攻爆jí腚メ 2021-12-09 08:10 461阅读 0赞

**1.循环队列模型与数组视图的对照
20130729134211421

2.实现代码:
const int MAX=3; //循环队列的固定长度

template
class myQue
{
private:
T que[MAX];
size_t front_index; //队首下标
size_t back_index; //队尾下标
size_t length; //队列长度
public:
myQue():front_index(0),back_index(0),length(0) //初始化队列
{
}

void pop() //岀队
{
if(empty())
{
cerr<<”error,the queue is empty.”<<endl;
return;
}
que[front_index]=T(); //把队首元素置空
front_index=(front_index+1)%MAX ; //计算队首下标的位置
length—;

}

void push(const T& val) //入队
{
if(full())
{
cerr<<”error,the queue is full.”<<endl;
return;
}
que[back_index]=val;
back_index=(back_index+1)%MAX ; //计算队尾下标的位置
length++;
}

T& front() //返回队首元素
{
return que[front_index];
}

size_t size() //返回队列大小
{
return length;;
}

bool empty() //判断队列是否为空
{
return length==0;
}

bool full() //判断队列是否为满
{
return length==MAX;
}

};

template
//打印队列所有元素
void print(myQue mq)
{
while(!mq.empty())
{
cout<<mq.front()<<ends;
mq.pop();
}
}

int main()
{
myQue mq;
mq.pop(); //error,the queue is empty.
mq.push(1);
mq.push(2);
mq.push(3);
mq.push(4); //error,the queue is full.
cout<<mq.size()<<endl; //3
print(mq); //1 2 3
cout<<endl<<endl;

mq.pop();
cout<<mq.size()<<endl; //2
mq.push(4);
print(mq); //2 3 4

}

运行结果:**

Center

另附队列的设配器类

**template
class myQue
{
private:
list que;
public:
void pop()
{
que.pop_front();
}

void push(T val)
{
que.push_back(val);
}

T& front()
{
return que.front();
}

size_t size()
{
return que.size();
}

bool empty()
{
return que.empty();
}

};

template
void print(myQue mq)
{
while(!mq.empty())
{
cout<<mq.front()<<ends;
mq.pop();
}
}

int main()
{
myQue mq;
mq.push(1);
mq.push(2);
mq.push(3);
cout<<mq.size()<<endl; //3
print(mq); //1 2 3
cout<<endl;

mq.pop();
cout<<mq.size()<<endl; //2
print(mq); //2 3

}**

发表评论

表情:
评论列表 (有 0 条评论,461人围观)

还没有评论,来说两句吧...

相关阅读