线性队列

来源:互联网 发布:混合视频矩阵 编辑:程序博客网 时间:2024/04/30 08:37

这里的线性结构实际上指的就是连续内存的意思,只不过使用“线性”这个词显得比较专业而已。前面一篇博客介绍了现象结构的处理方法,那么在这个基础之上我们是不是添加一些属性形成一种新的数据结构类型呢?答案是肯定的,队列便是其中的一种。

    队列的性质很简单:

    (1)队列有头部和尾部

    (2)队列从尾部压入数据

    (3)队列从头部弹出数据

    那么连续内存下的队列是怎么实现的呢?

    a)设计队列数据结构

[cpp] view plaincopy
  1. typedef struct _QUEUE_NODE  
  2. {  
  3.     int* pData;  
  4.     int length;  
  5.     int head ;  
  6.     int tail;  
  7.     int count;  
  8. }QUEUE_NODE;  
    b)申请队列内存

[cpp] view plaincopy
  1. QUEUE_NODE* alloca_queue(int number)  
  2. {  
  3.     QUEUE_NODE* pQueueNode;  
  4.     if( 0 == number)  
  5.         return NULL;  
  6.   
  7.     pQueueNode = (QUEUE_NODE*)malloc(sizeof(QUEUE_NODE));  
  8.     assert(NULL != pQueueNode);  
  9.     memset(pQueueNode, 0, sizeof(QUEUE_NODE));  
  10.   
  11.     pQueueNode->pData = (int*)malloc(sizeof(int) * number);  
  12.     if(NULL == pQueueNode->pData){  
  13.         free(pQueueNode);  
  14.         return NULL;  
  15.     }  
  16.   
  17.     pQueueNode->length = number;  
  18.     return pQueueNode;  
  19. }  
    c)释放队列内存

[cpp] view plaincopy
  1. STATUS delete_queue(const QUEUE_NODE* pQueueNode)  
  2. {  
  3.     if(NULL == pQueueNode)   
  4.         return FALSE;  
  5.       
  6.     assert(NULL != pQueueNode->pData);  
  7.       
  8.     free(pQueueNode->pData);  
  9.     free((void*)pQueueNode);  
  10.     return TRUE;  
  11. }  
    d)把数据压入队列

[cpp] view plaincopy
  1. STATUS insert_queue(QUEUE_NODE* pQueueNode, int value)  
  2. {  
  3.     if(NULL == pQueueNode)  
  4.         return FALSE;  
  5.   
  6.     if(pQueueNode->length == pQueueNode->count)  
  7.         return FALSE;  
  8.   
  9.     pQueueNode->pData[pQueueNode->tail] = value;  
  10.     pQueueNode->tail = (pQueueNode->tail + 1) % pQueueNode->length;    
  11.     pQueueNode->count ++;  
  12.     return TRUE;  
  13. }  
    e)把数据弹出队列

[cpp] view plaincopy
  1. STATUS get_queue_data(QUEUE_NODE* pQueueNode, int* value)  
  2. {  
  3.     if(NULL == pQueueNode || NULL == value)  
  4.         return FALSE;  
  5.   
  6.     if(0 == pQueueNode->count)  
  7.         return FALSE;  
  8.   
  9.     *value = pQueueNode->pData[pQueueNode->head];  
  10.     pQueueNode-> pData[pQueueNode->head] = 0;   
  11.     pQueueNode-> count --;  
  12.     pQueueNode->head = (pQueueNode->head + 1) % pQueueNode->length;  
  13.     return TRUE;  
  14. }  
    f)统计当前队列中有多少数据

[cpp] view plaincopy
  1. int  get_total_number(const QUEUE_NODE* pQueueNode)  
  2. {  
  3.     if(NULL == pQueueNode)  
  4.         return 0;  
  5.   
  6.     return pQueueNode->count;  
  7. }  
    g)查看队列中初始化的时候总长度是多少

[cpp] view plaincopy
  1. int  get_total_number(const QUEUE_NODE* pQueueNode)  
  2. {  
  3.     if(NULL == pQueueNode)  
  4.         return 0;  
  5.   
  6.     return pQueueNode->length;  
0 0