靜態佇列,迴圈陣列實現

惠hiuj發表於2024-05-07
/********************************************************************************************************
*
*	file name:	Zqh_佇列實現.c
* 	author	 :	keyword2024@163.com
* 	date	 :	2024/05/05
* 	function :	實現佇列的增刪改查
*	note	 :	模板
*	
*  Copyright (c)  2023-2024   keyword2024@163.com    All right Reserved
* ******************************************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

int len;//全域性變數,靜態佇列的實際有效長度,即實際存放了len個數
typedef struct Queue
{
	int *pBase;
	int front;
	int rear; 
} QUEUE,*PQUEUE;

PQUEUE creat_queue();
bool enter_queue(PQUEUE,int);
bool full_queue(PQUEUE);
bool empty_queue(PQUEUE);
void traverse_queue(PQUEUE);
bool out_queue(PQUEUE,int *);

int main()
{	//建立靜態佇列,並定義出隊資料的儲存在變數data_save中
	int data_save;
	PQUEUE pQueue = creat_queue();
	//將資料入隊,並遍歷輸出佇列中的資料
	enter_queue(pQueue,1);
	enter_queue(pQueue,2);
	enter_queue(pQueue,3);
	enter_queue(pQueue,4);
       	traverse_queue(pQueue);
	//將資料出隊,並遍歷輸出佇列中的資料
	out_queue(pQueue,&data_save);
       	traverse_queue(pQueue);

	return 0;
}

/*
建立並初始化一個空的靜態佇列,返回指向該佇列的指標,此時首尾在佇列同一位置處
*/
PQUEUE creat_queue()
{
	printf("Input the length of the queue:\n");
	scanf("%d",&len);
	PQUEUE pQueue = (PQUEUE)malloc(sizeof(QUEUE));
	pQueue->pBase = (int *)malloc(sizeof(int)*(len+1));
	if(NULL==pQueue || NULL==pQueue->pBase)
	{
	   printf("malloc failed!");
	   exit(-1);
	}
	else
	{
	   pQueue->front = 0;
	   pQueue->rear = 0;
	}
	 return pQueue;
}

/*
判斷該靜態佇列是否滿
*/
bool full_queue(PQUEUE pQueue)
{
	if(pQueue->front == (pQueue->rear+1)%(len+1))
	   return true;
	else
	   return false;
}

/*
判斷該靜態佇列是否空
*/
bool empty_queue(PQUEUE pQueue)
{
	if(pQueue->front == pQueue->rear)
	   return true;
	else
	   return false;
}

/*
將變數val從隊尾入隊
*/
bool enter_queue(PQUEUE pQueue,int val)
{
	if(full_queue(pQueue))
	   return false;
	else
	{
	   pQueue->pBase[pQueue->rear] = val;
	   pQueue->rear = (pQueue->rear+1)%(len+1);
	   return true;
	}
}

/*
將資料出隊,並將其儲存在out_data指標指向的位置
*/
bool out_queue(PQUEUE pQueue,int *out_data)
{
	if(empty_queue(pQueue))
	   return false;
	else
	{
	   *out_data = pBase[pQueue->front];
   	   pQueue->front = (pQueue->front+1)%(len+1);
	   return true;
	}
}

/*
遍歷該靜態佇列,並自隊首向隊尾輸出佇列中的資料
*/
void traverse_queue(PQUEUE pQueue)
{
	if(empty_queue(pQueue))
		printf("there on datas in the queue!\n");
	else
	{
		int i = pQueue->front;
		printf("now datas in the queue are:\n");
		while(i != pQueue->rear)
		{
			printf("%d ",pQueue->pBase[i]);
			i = (i+1)%(len+1);
		}
		printf("\n");		
	}

	return ;
}


相關文章