4、环形队列的实现(C语言)


一、实现原理如下图所示

 

环形队列实现需注意以下四点(本质上是和“3、一个简单队列的实现”一样的):
(1)往队列中写数据
memcpy(&g_tQue[g_iWritePos],pNode,sizeof(T_QUEUE));
g_iWritePos = (g_iWritePos + 1) % QUEUE_SIZE_MAX;

(2)从队列中读出数据
memcpy(pNode,&g_tQue[g_iReadPos],sizeof(T_QUEUE));
g_iReadPos = (g_iReadPos + 1) % QUEUE_SIZE_MAX;
(3)队列放满数据
((g_iWritePos + 1) % QUEUE_SIZE_MAX) == g_iReadPos),下一个要写的位置等于要读的位置,
则队列放满,实际上队列满的时候,里边存放的QUEUE_SIZE_MAX - 1个数据,这样做是为了和空
队列加以区分管

(4)队列为空(没有数据)
g_iWritePos == g_iReadPos,当前要写的位置等于当前要写的位置,则队列为空
二、代码实现如下

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 
 5 #define QUEUE_SIZE_MAX        10            
 6 #define MY_BUF_SIZE           128
 7 
 8 typedef struct{
 9     int type;
10     int reserve;
11     int buf[MY_BUF_SIZE];
12 }T_QUEUE;
13 
14 static T_QUEUE g_tQue[QUEUE_SIZE_MAX];
15 
16 static int g_iReadPos = 0;
17 static int g_iWritePos = 0;;
18 
19 static int isFull(void)
20 {
21     return (((g_iWritePos + 1) % QUEUE_SIZE_MAX) == g_iReadPos);
22 }
23 
24 static int isEmpty(void)
25 {
26     return (g_iWritePos == g_iReadPos);
27 }
28 
29 static int PutData(T_QUEUE *pNode)
30 {
31     if (isFull())
32     {
33         printf("queque is overflow!\r\n");
34         return -1;
35     }
36     else
37     {
38         memcpy(&g_tQue[g_iWritePos],pNode,sizeof(T_QUEUE));    
39         g_iWritePos = (g_iWritePos + 1) % QUEUE_SIZE_MAX;
40         return 0;
41     }
42 }
43 
44 static int GetData(T_QUEUE *pNode)
45 {
46     if (isEmpty())
47     {
48         printf("queque is empty!\r\n");
49         return -1;
50     }
51     else
52     {
53         memcpy(pNode,&g_tQue[g_iReadPos],sizeof(T_QUEUE));
54         g_iReadPos = (g_iReadPos + 1) % QUEUE_SIZE_MAX;
55     }
56     
57 }

猜你喜欢

转载自www.cnblogs.com/sbtblogs/p/11332347.html