c++循环队列(链式存储)

#pragma once
#include<iostream>
#include<string>
using namespace std;

template<class T>
class QuNode
{
public:
	T data;
	QuNode<T>* next;
};
template<class T>
class LinkQueue
{
private:
	QuNode<T>* front,*rear;
public:
	LinkQueue();
	LinkQueue(LinkQueue<T>& s);
	~LinkQueue();
	int Length();
	bool Empty();
	void Clear();
	bool InQueue(T e);
	bool OutQueue(T& e);
	bool getHead(T& e);
};
#include"链队列.hpp"
#include<iostream>
#include<string>
using namespace std;
template<class T>
LinkQueue<T>::LinkQueue()
{
	this->front = this->rear = new QuNode<T>;
	front->next = NULL;
}
template<class T>
LinkQueue<T>::LinkQueue(LinkQueue<T>& s)
{
	this->front = this->rear = new QuNode<T>;
	QuNode<T>* q = s.front;
	while (q != NULL)
	{
		QuNode<T>* p =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
循环队列可以使用顺序存储结构或链式存储结构实现。以下是使用 C++ 描述的循环队列在顺序循环队列或链队上的操作实现。 ## 顺序循环队列 ### 定义循环队列的结构体 ```c++ #define MAXSIZE 100 // 循环队列的最大长度 typedef struct { int data[MAXSIZE]; // 存储队列元素的数组 int front; // 头指针,指向队首元素 int rear; // 尾指针,指向队尾元素的下一个位置 } SqQueue; ``` ### 初始化循环队列 ```c++ void InitQueue(SqQueue &Q) { Q.front = Q.rear = 0; } ``` ### 判断循环队列是否为空 ```c++ bool IsEmpty(SqQueue Q) { return Q.front == Q.rear; } ``` ### 判断循环队列是否已满 ```c++ bool IsFull(SqQueue Q) { return (Q.rear + 1) % MAXSIZE == Q.front; } ``` ### 入队操作 ```c++ bool EnQueue(SqQueue &Q, int x) { if (IsFull(Q)) { return false; // 队列已满,无法入队 } Q.data[Q.rear] = x; Q.rear = (Q.rear + 1) % MAXSIZE; // 循环队列的下一个位置 return true; } ``` ### 出队操作 ```c++ bool DeQueue(SqQueue &Q, int &x) { if (IsEmpty(Q)) { return false; // 队列为空,无法出队 } x = Q.data[Q.front]; Q.front = (Q.front + 1) % MAXSIZE; // 循环队列的下一个位置 return true; } ``` ## 链式循环队列 ### 定义循环队列的结构体 ```c++ typedef struct LNode { int data; struct LNode *next; } LNode, *LinkList; typedef struct { LinkList front; // 头指针,指向队首元素 LinkList rear; // 尾指针,指向队尾元素 } LinkQueue; ``` ### 初始化循环队列 ```c++ void InitQueue(LinkQueue &Q) { Q.front = Q.rear = new LNode; Q.front->next = NULL; } ``` ### 判断循环队列是否为空 ```c++ bool IsEmpty(LinkQueue Q) { return Q.front == Q.rear; } ``` ### 入队操作 ```c++ void EnQueue(LinkQueue &Q, int x) { LNode *p = new LNode; p->data = x; p->next = NULL; Q.rear->next = p; Q.rear = p; // 尾指针后移 } ``` ### 出队操作 ```c++ bool DeQueue(LinkQueue &Q, int &x) { if (IsEmpty(Q)) { return false; // 队列为空,无法出队 } LNode *p = Q.front->next; x = p->data; Q.front->next = p->next; if (Q.rear == p) { Q.rear = Q.front; // 队列中只有一个元素,出队后尾指针指向头结点 } delete p; return true; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值