用c++实现链式队列的基本操作
时间: 2023-06-06 09:05:57 浏览: 66
好的,我可以回答这个问题。链式队列的基本操作包括:初始化队列、判断队列是否为空、入队、出队、取队头元素以及清空队列。以下是用 C 语言实现链式队列基本操作的示例代码:
```
#include<stdlib.h>
#include<stdio.h>
#define MaxSize 50
typedef struct node
{
int data;
struct node *pNext;
}Node, *pNode;
typedef struct queue
{
pNode front;
pNode rear;
}Queue, *pQueue;
//初始化队列
void InitQueue(pQueue q)
{
q->front = q->rear = (pNode)malloc(sizeof(Node));
if(NULL == q->front)
{
printf("初始化队列失败!");
exit(-1);
}
q->front->pNext = NULL;
}
//判断队列是否为空
int IsEmpty(pQueue q)
{
return q->front == q->rear ? 1 : 0;
}
//入队
void EnQueue(pQueue q, int value)
{
pNode pNew = (pNode)malloc(sizeof(Node));
if(NULL == pNew)
{
printf("入队失败!");
return;
}
pNew->data = value;
pNew->pNext = NULL;
q->rear->pNext = pNew;
q->rear = pNew;
}
//出队
int DeQueue(pQueue q)
{
if(IsEmpty(q))
{
printf("队列为空,无法出队!");
return -1;
}
pNode p = q->front->pNext;
int value = p->data;
q->front->pNext = p->pNext;
if(q->rear == p)
q->rear = q->front; //更新尾指针
free(p);
return value;
}
//取队头元素
int GetHead(pQueue q)
{
if(IsEmpty(q))
{
printf("队列为空,无法获取头元素!");
return -1;
}
return q->front->pNext->data;
}
//清空队列
void ClearQueue(pQueue q)
{
pNode p = q->front->pNext;
pNode qNode;
while(p)
{
qNode = p;
p = p->pNext;
free(qNode);
}
q->front = q->rear;
}
int main()
{
Queue q;
InitQueue(&q);
int i;
for(i = 1; i <= MaxSize; ++i)
EnQueue(&q, i);
printf("队列头元素为:%d\n", GetHead(&q));
printf("出队的元素为:");
while(!IsEmpty(&q))
printf("%d ", DeQueue(&q));
printf("\n");
ClearQueue(&q);
return 0;
}
```
请注意,这里的回答仅供参考,如有需要请自行验证代码的正确性。