設從鍵盤輸入一整數序列a1,a2,…an,試編程實現:當ai>0時,ai進隊,當ai<0時,將隊首元素出隊,當ai=0時,表示輸入結束。要求將隊列處理成環形隊列,使用環形隊列算法庫中定義的數據類型及算法,程序中只包括一個函數(main函數),入隊和出隊等操作直接在main函數中調用即可。當進隊出隊異常(如隊滿)時,要打印出錯信息
頭文件:sqqueue.h,包含定義順序環形隊列數據結構的代碼、宏定義、要實現算法的函數的聲明
[cpp] view plain copy
#ifndef SQQUEUE_H_INCLUDED
#define SQQUEUE_H_INCLUDED
#define MaxSize 5
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int front,rear; /*隊首和隊尾指針*/
} SqQueue;
void InitQueue(SqQueue *&q); //初始化順序環形隊列
void DestroyQueue(SqQueue *&q); //銷燬順序環形隊列
bool QueueEmpty(SqQueue *q); //判斷順序環形隊列是否爲空
int QueueLength(SqQueue *q); //返回隊列中元素個數,也稱隊列長度
bool enQueue(SqQueue *&q,ElemType e); //進隊
bool deQueue(SqQueue *&q,ElemType &e); //出隊
#endif // SQQUEUE_H_INCLUDED
源文件:sqqueue.cpp,包含實現各種算法的函數的定義
[cpp] view plain copy
#include <stdio.h>
#include <malloc.h>
#include "sqqueue.h"
void InitQueue(SqQueue *&q) //初始化順序環形隊列
{
q=(SqQueue *)malloc (sizeof(SqQueue));
q->front=q->rear=0;
}
void DestroyQueue(SqQueue *&q) //銷燬順序環形隊列
{
free(q);
}
bool QueueEmpty(SqQueue *q) //判斷順序環形隊列是否爲空
{
return(q->front==q->rear);
}
int QueueLength(SqQueue *q) //返回隊列中元素個數,也稱隊列長度
{
return (q->rear-q->front+MaxSize)%MaxSize;
}
bool enQueue(SqQueue *&q,ElemType e) //進隊
{
if ((q->rear+1)%MaxSize==q->front) //隊滿上溢出
return false;
q->rear=(q->rear+1)%MaxSize;
q->data[q->rear]=e;
return true;
}
bool deQueue(SqQueue *&q,ElemType &e) //出隊
{
if (q->front==q->rear) //隊空下溢出
return false;
q->front=(q->front+1)%MaxSize;
e=q->data[q->front];
return true;
}
main.cpp
[cpp] view plain copy
#include <stdio.h>
#include "sqqueue.h"
int main()
{
ElemType e;
SqQueue *q;
printf("(1)初始化隊列q\n");
InitQueue(q);
printf("(2)依次進隊列元素a,b,c\n");
if (enQueue(q,'a')==0) printf("隊滿,不能進隊\n");
if (enQueue(q,'b')==0) printf("隊滿,不能進隊\n");
if (enQueue(q,'c')==0) printf("隊滿,不能進隊\n");
printf("(3)隊列爲%s\n",(QueueEmpty(q)?"空":"非空"));
if (deQueue(q,e)==0)
printf("隊空,不能出隊\n");
else
printf("(4)出隊一個元素%c\n",e);
printf("(5)隊列q的元素個數:%d\n",QueueLength(q));
printf("(6)依次進隊列元素d,e,f\n");
if (enQueue(q,'d')==0) printf("隊滿,不能進隊\n");
if (enQueue(q,'e')==0) printf("隊滿,不能進隊\n");
if (enQueue(q,'f')==0) printf("隊滿,不能進隊\n");
printf("(7)隊列q的元素個數:%d\n",QueueLength(q));
printf("(8)出隊列序列:");
while (!QueueEmpty(q))
{
deQueue(q,e);
printf("%c ",e);
}
printf("\n");
printf("(9)釋放隊列\n");
DestroyQueue(q);
return 0;
}