項目原因,需要寫一個隊列來存儲串口實時輸出的字符串。看了網上很多博文和一些數據結構的數據,給的例子都是實現對單個數字或者字符的隊列操作,並沒有實現在隊列中存儲字符串。這裏分享一種可以實現的方法。
關於隊列的一些基本的概念這裏就不在介紹,下面直接上代碼。
主要實現了:
將字符串存入隊列之中,代碼中的 MAXSIZE 是最大的隊列長度。實際中由於夠成了循環隊列,所以這個最大存儲長度只有(MAXSIZE-1)。後面的二維數組 ais_data[MAXSIZE][250] 中250是隊列中的一次存儲字符串的最大的長度。
總體來說:在可以確定隊列的長度的最大值的情況下,推薦使用循環隊列。如果無法預知隊列的長度,可以使用鏈表隊列。
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
#include <string.h>
#define MAXSIZE 20
/*循環隊列對的順序存儲結構*/
typedef struct
{
char ais_data[MAXSIZE][250]; //隊列中的二維數組元素
int front; //頭指針
int rear; //尾指針
}sqQueue;
/*初始化一個空隊列*/
int InitQueue(sqQueue *Q)
{
Q->front=0; //結構體指針
Q->rear=0;
return 1;
}
/* 將隊列清空 */
int ClearQueue(sqQueue *Q)
{
Q -> front = 0;
Q -> rear = 0;
return 1;
}
/*返回隊列當前長度*/
int QueueLength(const sqQueue *Q)
{
return ((Q->rear - Q->front+ MAXSIZE)%MAXSIZE);
/* 返回隊列中元素的個數 */
}
/*循環隊列入隊操作 e爲插入的元素*/
int EnQueue(sqQueue *Q,char* e)
{
if((Q->rear+1)%MAXSIZE==Q->front) /*隊列已滿*/
{
return 0;
}
strcpy(Q->ais_data[Q->rear],e); //將元素e賦值給隊尾
Q->rear=(Q->rear+1)%MAXSIZE; //如果指向最後一位則轉回到數組頭
return 1;
}
/*若隊列不爲空,則刪除Q中隊頭元素,用e值返回*/
int DeQueue(sqQueue *Q,char *e)
{
if (Q->front==Q->rear) /*隊列爲空判斷*/
{
return 0;
}
strcpy(e, Q->ais_data[Q->front]);
Q->front=(Q->front+1)%MAXSIZE;
return 1;
}
測試運行主函數
void main(void)
{
int a,b,Qlength;
sqQueue Q;
char ais[250];
int i=0;
InitQueue(&Q); //初始化一個空隊列
a = QueueLength(&Q); //查看隊列長度
printf("隊列長度爲%d\n",a);
EnQueue(&Q,"2019-09-02"); //隊列插入元素
a = QueueLength(&Q); //查看隊列長度
printf("隊列長度爲%d\n",a);
memset(ais,0,250); //清空歷史數據
DeQueue(&Q,ais); //隊列元素出隊
printf("隊列中的元素是 %s\r\n",ais);
for(i=0;i<15;i++) //循環插入隊列
{
EnQueue(&Q,"2019-09-03");
}
a = QueueLength(&Q);
printf("隊列長度爲%d\n",a);
for(i=0;i<15;i++)
{
DeQueue(&Q,ais);
printf("隊列中的元素是 %s\r\n",ais);
a = QueueLength(&Q);
printf("隊列長度爲%d\n",a);
}
a = QueueLength(&Q);
printf("隊列長度爲%d\n",a);
}
好奇怪,我格式明明是正確的。顯示就亂了,額將就看下吧。