共计 1377 个字符,预计需要花费 4 分钟才能阅读完成。
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 10
#define TRUE 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType *base; // 数组基地址,动静分配内存
int front; // 头指针
int rear; // 尾指针
}Queue;
Status InitQueue(Queue* Q); // 初始化
Status InsertQueue(Queue* Q, ElemType e);// 入队
Status DeleteQueue(Queue* Q, ElemType* e); // 出队
Status LengthQueue(Queue* Q); // 获取队长
void DstoryQueue(Queue *Q); // 销毁队
int main()
{
Queue Q;
ElemType e;
int n, a;
if (InitQueue(&Q) == 1)
printf("创立循环队列胜利!\n");
printf("输出插入队尾元素个数:");
scanf("%d", &n);
printf("输出插入队尾元素:");
if (n != 0) // 判断队空
{for (int i = 0; i < n; i++)
{scanf("%d", &e);
a = InsertQueue(&Q, e);
}
}
else
a = -1;
if (a == 1) {printf("插入胜利!\n");
printf("队长为:%d\n", LengthQueue(&Q));
}
if (a==0)
printf("队已满!无奈持续插入了!\n");
if (DeleteQueue(&Q, &e) == 1)
{printf("删除队首元素为:%d\n", e);
}
else
printf("队为空!无奈持续删除了!\n");
printf("删除后队长为:%d\n", LengthQueue(&Q));
DstoryQueue(&Q);
printf("销毁结束!");
return 0;
}
Status InitQueue(Queue* Q)
{Q->base = (Queue*)malloc(sizeof(ElemType) * MaxSize);
if (!Q->base)
exit(0);
Q->front = Q->rear = 0;
return TRUE;
}
Status InsertQueue(Queue *Q, ElemType e)
{if ((Q->rear + 1) % MaxSize == Q->front)
return ERROR;
Q->base[Q->rear] = e;
Q->rear = (Q->rear + 1) % MaxSize;
return TRUE;
}
Status DeleteQueue(Queue* Q, ElemType* e)
{if (Q->front == Q->rear)
return ERROR;
*e = Q->base[Q->front];
Q->front = (Q->front + 1) % MaxSize;
return TRUE;
}
Status LengthQueue(Queue* Q)
{return ((Q->rear-Q->front+MaxSize)%MaxSize);
}
void DstoryQueue(Queue* Q)
{free(Q->base);
Q->base = NULL;
Q->front = Q->rear = 0;
}
正文完