字符串队列c语言,C语言实现循环队列(队列可存储字符串)
項(xiàng)目原因,需要寫(xiě)一個(gè)隊(duì)列來(lái)存儲(chǔ)串口實(shí)時(shí)輸出的字符串。看了網(wǎng)上很多博文和一些數(shù)據(jù)結(jié)構(gòu)的數(shù)據(jù),給的例子都是實(shí)現(xiàn)對(duì)單個(gè)數(shù)字或者字符的隊(duì)列操作,并沒(méi)有實(shí)現(xiàn)在隊(duì)列中存儲(chǔ)字符串。這里分享一種可以實(shí)現(xiàn)的方法。
關(guān)于隊(duì)列的一些基本的概念這里就不在介紹,下面直接上代碼。
主要實(shí)現(xiàn)了:
將字符串存入隊(duì)列之中,代碼中的MAXSIZE 是最大的隊(duì)列長(zhǎng)度。實(shí)際中由于夠成了循環(huán)隊(duì)列,所以這個(gè)最大存儲(chǔ)長(zhǎng)度只有(MAXSIZE-1)。后面的二維數(shù)組?ais_data[MAXSIZE][250] 中250是隊(duì)列中的一次存儲(chǔ)字符串的最大的長(zhǎng)度。
總體來(lái)說(shuō):在可以確定隊(duì)列的長(zhǎng)度的最大值的情況下,推薦使用循環(huán)隊(duì)列。如果無(wú)法預(yù)知隊(duì)列的長(zhǎng)度,可以使用鏈表隊(duì)列。
#include#include#include#include#include #define MAXSIZE 20
/*循環(huán)隊(duì)列對(duì)的順序存儲(chǔ)結(jié)構(gòu)*/
typedef struct
{
char ais_data[MAXSIZE][250]; //隊(duì)列中的二維數(shù)組元素
int front; //頭指針
int rear; //尾指針
}sqQueue;
/*初始化一個(gè)空隊(duì)列*/
int InitQueue(sqQueue *Q)
{
Q->front=0; //結(jié)構(gòu)體指針
Q->rear=0;
return 1;
}
/* 將隊(duì)列清空 */
int ClearQueue(sqQueue *Q)
{
Q -> front = 0;
Q -> rear = 0;
return 1;
}
/*返回隊(duì)列當(dāng)前長(zhǎng)度*/
int QueueLength(const sqQueue *Q)
{
return ((Q->rear - Q->front+ MAXSIZE)%MAXSIZE);
/* 返回隊(duì)列中元素的個(gè)數(shù) */
}
/*循環(huán)隊(duì)列入隊(duì)操作 e為插入的元素*/
int EnQueue(sqQueue *Q,char* e)
{
if((Q->rear+1)%MAXSIZE==Q->front) /*隊(duì)列已滿*/
{
return 0;
}
strcpy(Q->ais_data[Q->rear],e); //將元素e賦值給隊(duì)尾
Q->rear=(Q->rear+1)%MAXSIZE; //如果指向最后一位則轉(zhuǎn)回到數(shù)組頭
return 1;
}
/*若隊(duì)列不為空,則刪除Q中隊(duì)頭元素,用e值返回*/
int DeQueue(sqQueue *Q,char *e)
{
if (Q->front==Q->rear) /*隊(duì)列為空判斷*/
{
return 0;
}
strcpy(e, Q->ais_data[Q->front]);
Q->front=(Q->front+1)%MAXSIZE;
return 1;
}
測(cè)試運(yùn)行主函數(shù)
void main(void)
{
int a,b,Qlength;
sqQueue Q;
char ais[250];
int i=0;
InitQueue(&Q); //初始化一個(gè)空隊(duì)列
a = QueueLength(&Q); //查看隊(duì)列長(zhǎng)度
printf("隊(duì)列長(zhǎng)度為%d\n",a);
EnQueue(&Q,"2019-09-02"); //隊(duì)列插入元素
a = QueueLength(&Q); //查看隊(duì)列長(zhǎng)度
printf("隊(duì)列長(zhǎng)度為%d\n",a);
memset(ais,0,250); //清空歷史數(shù)據(jù)
DeQueue(&Q,ais); //隊(duì)列元素出隊(duì)
printf("隊(duì)列中的元素是 %s\r\n",ais);
for(i=0;i<15;i++) //循環(huán)插入隊(duì)列
{
EnQueue(&Q,"2019-09-03");
}
a = QueueLength(&Q);
printf("隊(duì)列長(zhǎng)度為%d\n",a);
for(i=0;i<15;i++)
{
DeQueue(&Q,ais);
printf("隊(duì)列中的元素是 %s\r\n",ais);
a = QueueLength(&Q);
printf("隊(duì)列長(zhǎng)度為%d\n",a);
}
a = QueueLength(&Q);
printf("隊(duì)列長(zhǎng)度為%d\n",a);
}
好奇怪,我格式明明是正確的。顯示就亂了,額將就看下吧。
總結(jié)
以上是生活随笔為你收集整理的字符串队列c语言,C语言实现循环队列(队列可存储字符串)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: linux7自带haprox版本,Cen
- 下一篇: c语言的舞蹈机器人开题报告范文,现代舞编