第七週—項目2 - 建立鏈隊算法庫

問題及代碼:


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

int main()
{
    ElemType e;
    LiQueue *q;
    printf("(1)初始化鏈隊q\n");
    InitQueue(q);
    printf("(2)依次進鏈隊元素a,b,c\n");
    enQueue(q,'a');
    enQueue(q,'b');
    enQueue(q,'c');
    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");
    enQueue(q,'d');
    enQueue(q,'e');
    enQueue(q,'f');
    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 <stdio.h>
#include <malloc.h>
#include "liqueue.h"

void InitQueue(LiQueue *&q)  //初始化鏈隊
{
    q=(LiQueue *)malloc(sizeof(LiQueue));
    q->front=q->rear=NULL;
}
void DestroyQueue(LiQueue *&q)  //銷燬鏈隊
{
    QNode *p=q->front,*r;   //p指向隊頭數據節點
    if (p!=NULL)            //釋放數據節點佔用空間
    {
        r=p->next;
        while (r!=NULL)
        {
            free(p);
            p=r;
            r=p->next;
        }
    }
    free(p);
    free(q);                //釋放鏈隊節點佔用空間
}
bool QueueEmpty(LiQueue *q)  //判斷鏈隊是否爲空
{
    return(q->rear==NULL);
}
int QueueLength(LiQueue *q)  //返回隊列中數據元素個數
{
    int n=0;
    QNode *p=q->front;
    while (p!=NULL)
    {
        n++;
        p=p->next;
    }
    return(n);
}
void enQueue(LiQueue *&q,ElemType e)  //入隊
{
    QNode *p;
    p=(QNode *)malloc(sizeof(QNode));
    p->data=e;
    p->next=NULL;
    if (q->rear==NULL)      //若鏈隊爲空,則新節點是隊首節點又是隊尾節點
        q->front=q->rear=p;
    else
    {
        q->rear->next=p;    //將*p節點鏈到隊尾,並將rear指向它
        q->rear=p;
    }
}
bool deQueue(LiQueue *&q,ElemType &e)   //出隊
{
    QNode *t;
    if (q->rear==NULL)      //隊列爲空
        return false;
    t=q->front;             //t指向第一個數據節點
    if (q->front==q->rear)  //隊列中只有一個節點時
        q->front=q->rear=NULL;
    else                    //隊列中有多個節點時
        q->front=q->front->next;
    e=t->data;
    free(t);
    return true;
}

#ifndef LIQUEUE_H_INCLUDED
#define LIQUEUE_H_INCLUDED


typedef char ElemType;
typedef struct qnode
{
    ElemType data;
    struct qnode *next;
} QNode;        //鏈隊數據結點類型定義

typedef struct
{
    QNode *front;
    QNode *rear;
} LiQueue;          //鏈隊類型定義
void InitQueue(LiQueue *&q);  //初始化鏈隊
void DestroyQueue(LiQueue *&q);  //銷燬鏈隊
bool QueueEmpty(LiQueue *q);  //判斷鏈隊是否爲空
int QueueLength(LiQueue *q);  //返回隊列中數據元素個數
void enQueue(LiQueue *&q,ElemType e);  //入隊
bool deQueue(LiQueue *&q,ElemType &e);   //出隊
#endif // LIQUEUE_H_INCLUDED


輸出及結果:


分析:


建立算法庫,爲以後編程提供便利

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