#include <iostream>
#include <cstdlib>
using namespace std;
const int MAXSIZE = 10; //队列的容量
//单个结点结构体
typedef struct Node
{
int data;
struct Node *next;
}pNode;
//队列结构体
typedef struct Queue
{
pNode *front;
pNode *rear;
int _size;
}pQueue;
//函数实现
//===============================
//创建空队列
pQueue *CreateEmptyQueue()
{
pQueue *p = (pQueue *)malloc(sizeof(pQueue));
if (!p)
return NULL;
p->front = (pNode *)malloc(sizeof(pNode));
if (!p->front)
return NULL;
p->rear= (pNode *)malloc(sizeof(pNode));
if (!p->rear)
return NULL;
//队列容量初始化为零
p->_size = 0;
return p;
}
//判断队列是否为空
bool IsEmptyQueue(pQueue *p)
{
if (!p->_size) //队列为空
return true;
else
return false;
}
//判断是否满队列
bool IsFullQueue(pQueue *p)
{
if (p->_size == MAXSIZE)
return true;
else
return false;
}
//入队
void PushDataToQueue(pQueue *p)
{
//判断队列是否已满
if (IsFullQueue(p))
return; //如果队列已满则退出
//否则申请新结点
pNode *dF= (pNode *)malloc(sizeof(pNode));
if (!dF)
return;
cout << "请输入数据:"; cin >> dF->data;
//如果队列为空将数据放在队头的位置
if (IsEmptyQueue(p))
p->front = dF;
//否则放在队尾的位置
else
p->rear->next = dF;
p->_size++;
//最后将rear指向队尾结点
p->rear = dF;
}
//返回队头元素并且释放队头结点
int PopDataFromQueue(pQueue *p)
{
if (IsEmptyQueue(p))
return -1;
int ReturnNumber;
pNode *pr = p->front; //让pr指向队头结点
ReturnNumber = pr->data;
p->front = p->front->next;
free(pr);
p->_size--;
return ReturnNumber;
}
//===============================
int main()
{
//创建空队列
pQueue *p = CreateEmptyQueue();
//入队
for (int i = 0; i < 10; ++i)
PushDataToQueue(p);
//返回队头元素
cout << "正在出队的队头元素为:" << PopDataFromQueue(p) << endl;
//依次出对所有元素
cout << "剩下的元素为:" << endl;
for (int i = 0; i < MAXSIZE - 1; ++i)
cout << PopDataFromQueue(p) << " ";
return 0;
}
队列的链表实现
最新推荐文章于 2025-06-09 17:59:59 发布