第7周实践项目2 队列的链式存储结构及其基本运算的实现
生活随笔
收集整理的這篇文章主要介紹了
第7周实践项目2 队列的链式存储结构及其基本运算的实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
liqueue.cpp#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 *pre=q->front,*p;if(pre){p=pre->next;while(p){free(pre);pre=p;p=p->next;}free(pre);}free(q);
}
bool QueueEmpty(LiQueue *q) //判斷鏈隊是否為空
{return (q->rear==NULL);
}
int QueueLength(LiQueue *q) //返回隊列中數(shù)據(jù)元素個數(shù)
{int n=0;QNode *p=q->front;while(p){++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;q->rear=p;}
}
bool deQueue(LiQueue *&q,ElemType &e) //出隊(考慮空隊,只有一個數(shù)據(jù)節(jié)點,有多個節(jié)點以上,這三種情況)
{QNode *t;if(q->rear==NULL)return false;t=q->front;if(q->front==q->rear)q->front=q->rear=NULL;elseq->front=q->front->next;e=t->data;free(t);return true;
}
liqueue.h
#ifndef LIQUEUE_H_INCLUDED
#define LIQUEUE_H_INCLUDED
typedef char ElemType;
typedef struct qnode
{ElemType data;struct qnode *next;
} QNode; //鏈隊數(shù)據(jù)結(jié)點類型定義
typedef struct
{QNode *front;QNode *rear;
} LiQueue; //鏈隊類型定義
void InitQueue(LiQueue *&q); //初始化鏈隊
void DestroyQueue(LiQueue *&q); //銷毀鏈隊
bool QueueEmpty(LiQueue *q); //判斷鏈隊是否為空
int QueueLength(LiQueue *q); //返回隊列中數(shù)據(jù)元素個數(shù)
void enQueue(LiQueue *&q,ElemType e); //入隊
bool deQueue(LiQueue *&q,ElemType &e); //出隊
#endif // LIQUEUE_H_INCLUDED
main.cpp#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");elseprintf("(4)出隊一個元素%c\n",e);printf("(5)鏈隊q的元素個數(shù):%d\n",QueueLength(q));printf("(6)依次進鏈隊元素d,e,f\n");enQueue(q,'d');enQueue(q,'e');enQueue(q,'f');printf("(7)鏈隊q的元素個數(shù):%d\n",QueueLength(q));printf("(8)出鏈隊序列:");while (!QueueEmpty(q)){deQueue(q,e);printf("%c ",e);}printf("\n");printf("(9)釋放鏈隊\n");DestroyQueue(q);return 0;
}
總結(jié)
以上是生活随笔為你收集整理的第7周实践项目2 队列的链式存储结构及其基本运算的实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第7周实践项目1.1 环形队列中用队尾和
- 下一篇: 第7周项目实践2.1 用只有尾节点指针