队列

全部代码

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <assert.h>
  4 
  5 typedef struct node
  6 {
  7     int nValue;
  8     struct node *pNext;
  9 }MyQueue;
 10 
 11 typedef struct node2
 12 {
 13     int nCount;
 14     MyQueue *pHead;
 15     MyQueue *pTail;
 16 }Queue;
 17 
 18 void q_Init(Queue **ppQueue)
 19 {
 20     assert(ppQueue != NULL);
 21 
 22     *ppQueue = (Queue *)malloc(sizeof(Queue));
 23     if(NULL == *ppQueue)
 24     {
 25         printf("队列空间分配失败!\n");
 26         exit(-1);
 27     }
 28     (*ppQueue)->nCount = 0;
 29     (*ppQueue)->pHead = NULL;
 30     (*ppQueue)->pTail = NULL;
 31 }
 32 
 33 void q_Push(Queue *pQueue, int nNum)
 34 {
 35     MyQueue *pTemp = NULL;
 36 
 37     assert(pQueue!=NULL);
 38 
 39     //临时节点开辟空间
 40     pTemp = (MyQueue *)malloc(sizeof(MyQueue));
 41     if(NULL == pTemp)
 42     {
 43         printf("临时节点空间分配失败!\n");
 44         exit(-1);
 45     }
 46     pTemp->nValue = nNum;
 47     pTemp->pNext = NULL;
 48 
 49     //尾添加
 50     if(NULL == pQueue->pHead)
 51     {
 52         pQueue->pHead = pTemp;
 53     }
 54     else
 55     {
 56         pQueue->pTail->pNext = pTemp;
 57     }
 58     pQueue->pTail = pTemp;
 59 
 60     //更新队列中的元素
 61     ++pQueue->nCount;
 62 }
 63 
 64 int q_Pop(Queue *pQueue)
 65 {
 66     int nNum;
 67     MyQueue *pDel = NULL;
 68 
 69     assert(pQueue!=NULL && pQueue->pHead!=NULL);
 70 
 71     //头删除
 72     pDel = pQueue->pHead;
 73     nNum = pDel->nValue;
 74     //头下移
 75     pQueue->pHead = pQueue->pHead->pNext;
 76 
 77     //释放空间
 78     free(pDel);
 79     pDel = NULL;
 80 
 81     //更新队列中的元素
 82     --pQueue->nCount;
 83 
 84     //尾置空
 85     if(0 == pQueue->nCount)
 86     {
 87         pQueue->pTail = NULL;
 88     }
 89 
 90     return nNum;
 91 }
 92 
 93 int q_IsEmpty(Queue *pQueue)
 94 {
 95     assert(pQueue!=NULL);
 96 
 97     return 0==pQueue->nCount ? 1:0;
 98 }
 99 
100 int main(void)
101 {
102     Queue *pQueue = NULL;
103 
104     //初始化
105     q_Init(&pQueue);
106 
107     //添加
108     q_Push(pQueue, 10);
109     q_Push(pQueue, 20);
110 
111     printf("%d\n", q_Pop(pQueue));
112     printf("%d\n", q_Pop(pQueue));
113 
114     return 0;
115 }

 

posted @ 2017-11-01 10:54  c&z  阅读(192)  评论(0编辑  收藏  举报