总的实现代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXSIZE 200 // 队列的最大容量
typedef struct{
char name[100];
char id[100];
}ElemType;
typedef struct {
ElemType items[MAXSIZE];
int front;
int rear;
}Queue;
// 初始化队列
void InitQueue(Queue* q)
{
q->front = -1;
q->rear = -1;
}
// 判断队列是否为空
bool Empty(Queue* q)
{
return q->front == -1;
}
// 判断队列是否已满
bool Full(Queue* q)
{
return q->rear == MAXSIZE - 1;
}
// 入队操作
bool Push(Queue* q, ElemType value)
{
if (Full(q))
return false;
if (Empty(q))
q->front = 0; // 如果队列为空,更新队头
q->rear++; // 更新队尾
q->items[q->rear] = value; // 将新元素加入队列
return true;
}
// 出队操作
void Pop(Queue* q, ElemType *e)
{
if (Empty(q))
{
e = NULL;
return; // 返回
}
if (q->front == q->rear)
{
q->front = -1; // 如果队列只有一个元素,重置队列
q->rear = -1;
}
else
{
*e = q->items[q->front];
int i;
for(i = 0; i < q->rear - q->front; ++i)
{
q->items[i] = q->items[i + 1];
}
q->rear--;
}
return;
}
// 查看队头元素
ElemType* Front(Queue* q)
{
if (Empty(q))
return NULL; // 返回一个错误值
return &(q->items[q->front]);
}
int Size(Queue* q)
{
int count = q->rear - q->front + 1;
return count;
}
// 主函数示例
int main()
{
ElemType arr[20] = {
{"张三", "0x001"},
{"李四", "0x002"}
};
Queue queue;
InitQueue(&queue);
Push(&queue, arr[0]);
Push(&queue, arr[1]);
ElemType *e = Front(&queue);
printf("队首元素为:%s %s\n", e->name, e->id);
printf("队列中元素个数为:%d\n", Size(&queue));
Pop(&queue, e);
printf("队列中元素个数为:%d\n", Size(&queue));
e = Front(&queue);
if(e != NULL)
printf("队首元素为:%s %s\n", e->name, e->id);
if(Empty(&queue))
printf("队列空\n");
else
printf("队列非空\n");
if(Full(&queue))
printf("栈满");
else
printf("栈非满\n");
return 0;
}
没有回复内容