順序隊列的C語言實現


#include "stdio.h"
#include "stdlib.h"
#include "io.h"
#include "math.h"
#include "time.h"

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20 /* 存儲空間初始分配量 */

typedef int Status;
typedef int QElemType; /* QElemType類型根據實際情況而定,這里假設為int */

/* 循環隊列的順序存儲結構 */
typedef struct
{
QElemType data[MAXSIZE];
int front; /* 頭指針 */
int rear; /* 尾指針,若隊列不空,指向隊列尾元素的下一個位置 */
}SqQueue;

Status visit(QElemType c)
{
printf("%d ",c);
return OK;
}

/* 初始化一個空隊列Q */
Status InitQueue(SqQueue *Q)
{
Q->front=0;
Q->rear=0;
return OK;
}

/* 將Q清為空隊列 */
Status ClearQueue(SqQueue *Q)
{
Q->front=Q->rear=0;
return OK;
}

/* 若隊列Q為空隊列,則返回TRUE,否則返回FALSE */
Status QueueEmpty(SqQueue Q)
{
if(Q.front==Q.rear) /* 隊列空的標志 */
return TRUE;
else
return FALSE;
}

/* 返回Q的元素個數,也就是隊列的當前長度 */
int QueueLength(SqQueue Q)
{
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;      
}

/* 若隊列不空,則用e返回Q的隊頭元素,並返回OK,否則返回ERROR */
Status GetHead(SqQueue Q,QElemType *e)
{
if(Q.front==Q.rear) /* 隊列空 */
return ERROR;
*e=Q.data[Q.front];
return OK;
}

/* 若隊列未滿,則插入元素e為Q新的隊尾元素 */
Status EnQueue(SqQueue *Q,QElemType e)
{
if ((Q->rear+1)%MAXSIZE == Q->front) /* 隊列滿的判斷 */
return ERROR;
Q->data[Q->rear]=e; /* 將元素e賦值給隊尾 */
Q->rear=(Q->rear+1)%MAXSIZE;/* rear指針向后移一位置, */
/* 若到最后則轉到數組頭部 */
return OK;
}

/* 若隊列不空,則刪除Q中隊頭元素,用e返回其值 */
Status DeQueue(SqQueue *Q,QElemType *e)
{
if (Q->front == Q->rear) /* 隊列空的判斷 */
return ERROR;
*e=Q->data[Q->front]; /* 將隊頭元素賦值給e */
Q->front=(Q->front+1)%MAXSIZE; /* front指針向后移一位置, */
/* 若到最后則轉到數組頭部 */
return OK;
}

/* 從隊頭到隊尾依次對隊列Q中每個元素輸出 */
Status QueueTraverse(SqQueue Q)
{
int i;
i=Q.front;
while((i+Q.front)!=Q.rear)
{
visit(Q.data[i]);
i=(i+1)%MAXSIZE;
}
printf("\n");
return OK;
}

int main()
{
Status j;
int i=0,l;
QElemType d;
SqQueue Q;
InitQueue(&Q);
printf("初始化隊列后,隊列空否?%u(1:空 0:否)\n",QueueEmpty(Q));

printf("請輸入整型隊列元素(不超過%d個),-1為提前結束符: ",MAXSIZE-1);
do
{
/* scanf("%d",&d); */
d=i+100;
if(d==-1)
break;
i++;
EnQueue(&Q,d);
}while(i<MAXSIZE-1);

printf("隊列長度為: %d\n",QueueLength(Q));
printf("現在隊列空否?%u(1:空 0:否)\n",QueueEmpty(Q));
printf("連續%d次由隊頭刪除元素,隊尾插入元素:\n",MAXSIZE);
for(l=1;l<=MAXSIZE;l++)
{
DeQueue(&Q,&d);
printf("刪除的元素是%d,插入的元素:%d \n",d,l+1000);
/* scanf("%d",&d); */
d=l+1000;
EnQueue(&Q,d);
}
l=QueueLength(Q);

printf("現在隊列中的元素為: \n");
QueueTraverse(Q);
printf("共向隊尾插入了%d個元素\n",i+MAXSIZE);
if(l-2>0)
printf("現在由隊頭刪除%d個元素:\n",l-2);
while(QueueLength(Q)>2)
{
DeQueue(&Q,&d);
printf("刪除的元素值為%d\n",d);
}

j=GetHead(Q,&d);
if(j)
printf("現在隊頭元素為: %d\n",d);
ClearQueue(&Q);
printf("清空隊列后, 隊列空否?%u(1:空 0:否)\n",QueueEmpty(Q));
return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM