#include<stdio.h>
#include<malloc.h>
#include<conio.h>
#define QUEUESIZE 5
int length;
int flag = 0;
typedef struct Queue{
int head;//指向队头
int rear;//指向队尾
int *array;
}QUEUE;
void initQueue(QUEUE * pQueue){
pQueue->array = (int *)malloc(sizeof(int) * QUEUESIZE);//5
pQueue->head = 0;
pQueue->rear = 0;
printf("队列初始化成功!\n");
}
bool isEmpty(QUEUE * pQueue){
if(pQueue->head == pQueue->rear){
// printf("队列为空!\n");
return true;
}
else{
printf("队列为非空!\n");
return false;
}
}
bool isFull(QUEUE * pQueue){
if(pQueue->rear - pQueue->head == QUEUESIZE-1){
printf("%d",pQueue->rear);
printf("队列已满!\n");
return true;
}
else{
//printf("队列未满!\n");
return false;
}
}
bool enQueue(QUEUE * pQueue,int value){
if(isFull(pQueue)){
if(0 == flag){
pQueue->array[pQueue->rear] =value; //4
flag = 1;
// system("pause");
//printf("任意键继续!");
}
//exit(0);
return true;
}
else{
pQueue->array[pQueue->rear] = value; //rear 0 1 2 3
pQueue->rear++; // 1 2 3 4
return true;
}
}
int outQueue(QUEUE * pQueue,int value){
if(isEmpty(pQueue)){
system("pause");
printf("任意键退出!");
exit(0);
}
else{
value = pQueue->array[pQueue->head];
pQueue->array[pQueue->head] = 0;
pQueue->head++;
printf("出队元素是:%d\n",value);
return value;
}
}
int getLength(QUEUE * pQueue){
int len = (pQueue->rear - pQueue->head)+1;
printf("队列长度为:%d\n",len);
return len;
}
void traverseQueue(QUEUE * pQueue){
int i = pQueue->head;
while(i != pQueue->rear){
printf("%d ",pQueue->array[i]);
i++;
}
printf("%d\n",pQueue->array[i]);
}
void clearQueue(QUEUE * pQueue){
///这个数组的话可能只好置为0值这样子
int i = pQueue->head;
while(i != pQueue->rear) //如果没有到达rear位置,就循环
{
pQueue->array[i] = 0;
i++; //移到下一位置
}
pQueue->array[i] = 0;
}
//destroy Queue
void destroyQueue(QUEUE *pQueue){
//QUEUE * tempQ = &pQueue;
if(pQueue!=NULL){
free(pQueue->array);
}
if(pQueue->array[0]!= 0){
printf("队列成功销毁!\n");
pQueue = NULL;
pQueue = NULL;
}
else{
// printf("%d\n",pQueue->array[0]);
printf("队列销毁失败!\n");
}
}
int main(){
QUEUE queue;
initQueue(&queue);
printf("下面开始插入元素(入队):\n");
enQueue(&queue, 1); //rear = 1
enQueue(&queue, 2); //rear = 2
enQueue(&queue, 3); //rear = 3
enQueue(&queue, 4); //rear = 4
enQueue(&queue, 5); //rear = 4
enQueue(&queue, 6);
enQueue(&queue, 7);
enQueue(&queue, 8);
length = getLength(&queue);
//调用遍历队列的函数
traverseQueue(&queue);
int temp;
printf("下面开始删除元素(出队):\n");
temp = outQueue(&queue,temp);
temp = outQueue(&queue,temp);
traverseQueue(&queue);
printf("下面开始清空元素:\n");
clearQueue(&queue);
traverseQueue(&queue);
destroyQueue(&queue);
return 0;
}
顺序队列
最新推荐文章于 2025-07-20 12:45:35 发布