/*顺序队列的简要实现
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
struct QueueArray;
typedef int ElementType;
typedef struct QueueArray* PtrToQueue;
typedef PtrToQueue Queue;
struct QueueArray{
ElementType data[MAXSIZE];
int front;
int rear;
};
Queue InitQueue();/*初始化队列*/
void ClearQueue(Queue Q);/*清空队列*/
void QueueEmpty(Queue Q);/*检查队列是否为空*/
int QueueLength(Queue Q);/*获取队列长度*/
int GetHead(Queue Q);/*获取队列头元素*/
int EnQueue(Queue Q, ElementType e);/*入列*/
int DeQueue(Queue Q);/*出列*/
/*初始化队列*/
Queue InitQueue(){
Queue Q = malloc(sizeof(struct QueueArray));
Q->front = 0;
Q->rear = 0;
return Q;
}
/*清空队列*/
void ClearQueue(Queue Q){
Q->front = Q->rear = 0;
}
/*检查队列是否为空*/
void QueueEmpty(Queue Q){
if (Q->front == Q->rear)
printf("\n队列为空\n");
else
printf("\n队列不为空\n");
}
/*获取队列长度*/
int QueueLength(Queue Q){
return (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
}
/*获取队列头元素*/
int GetHead(Queue Q){
if (Q->front == Q->rear)
return NULL;
return Q->data[Q->front];
}
/*入列*/
int EnQueue(Queue Q, ElementType e){
if ((Q->rear + 1) % MAXSIZE == Q->front)
return NULL;
Q->data[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXSIZE;
return e;
}
/*出列*/
int DeQueue(Queue Q){
if (Q->front == Q->rear)
return NULL;
int e = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
return e;
}
void main(){
Queue Q;
Q = InitQueue();
printf("入列: \n");
for (int i = 1; i <= 10; i++){
printf(" %d",EnQueue(Q, i));
}
QueueEmpty(Q);
printf("队列长度为:%d\n", QueueLength(Q));
printf("队列头元素为:%d\n", GetHead(Q));
printf("\n");
printf("出列: \n");
for (int i = 1; i <= 5; i++){
printf("%d ",DeQueue(Q, i));
}
QueueEmpty(Q);
printf("队列长度为:%d\n", QueueLength(Q));
printf("队列头元素为:%d\n", GetHead(Q));
}
学习笔记之数据结构篇-05顺序队列
最新推荐文章于 2024-08-27 22:35:52 发布