第七週—項目1 - 建立順序環形隊列算法庫

問題及代碼:


/* 
 *Copyright(c)2015,煙臺大學計算機與控制工程學院 
 *All right reserved. 
 *文件名稱:main.cpp 
 *作者:程昂 
 *完成日期;2015年10月12日 
 *版本號;v1.0 
 * 
 *問題描述:建立順序環形隊列算法庫,定義順序環形隊列存儲結構,實現其基本運算,並完成測試。
 *程序輸出: 測試結果
*/  
#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;
}

#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;
}


#ifndef SQQUEUE_H_INCLUDED
#define SQQUEUE_H_INCLUDED


#define MaxSize 5
#include <stdio.h>
#include <malloc.h>
typedef char 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


輸出及結果:



分析:

建立環形鏈表算法庫,爲以後編程提供方便。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章