Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2980053
  • 博文数量: 272
  • 博客积分: 5544
  • 博客等级: 大校
  • 技术积分: 5496
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 00:48
个人简介

  每个人都要有一个骨灰级的爱好,不为金钱,而纯粹是为了在这个领域享受追寻真理的快乐。

文章分类

全部博文(272)

文章存档

2015年(2)

2014年(5)

2013年(25)

2012年(58)

2011年(182)

分类: LINUX

2013-03-09 19:20:41


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>

  4. #define Q_LEN 6

  5. typedef struct {
  6.     int *pBase;
  7.     int front;
  8.     int rear;
  9. }QUEUE;

  10. static void init(QUEUE *pQ) {
  11.     pQ->pBase = (int *)malloc(sizeof(int) * Q_LEN);
  12.     pQ->front = 0;
  13.     pQ->rear = 0;
  14. }

  15. static inline bool full_queue(QUEUE *pQ) {
  16.     if((pQ->rear + 1) % Q_LEN == pQ->front)
  17.         return true;
  18.     else
  19.         return false;
  20. }

  21. static bool en_queue(QUEUE *pQ, int val) {
  22.     if (full_queue(pQ)) {
  23.         printf("队列已满, %d 不能被加入队列\n", val);
  24.         return false;
  25.     } else {
  26.         pQ->pBase[pQ->rear] = val;
  27.         pQ->rear = (pQ->rear + 1) % Q_LEN;
  28.         return true;
  29.     }
  30. }

  31. static void traverse_queue(QUEUE *pQ) {
  32.     int idx = pQ->front;
  33.     while (idx != pQ->rear) {
  34.         printf("%d ", pQ->pBase[idx]);
  35.         idx = (idx + 1) % Q_LEN;
  36.     }
  37.     printf("\n");
  38. }

  39. static inline bool emput_queue(QUEUE *pQ) {
  40.     if (pQ->front == pQ->rear) {
  41.         return true;
  42.     } else {
  43.         return false;
  44.     }
  45. }

  46. static bool out_queue(QUEUE *pQ, int *pVal) {
  47.     if (emput_queue(pQ)) {
  48.         return false;
  49.     } else {
  50.         *pVal = pQ->pBase[pQ->front];
  51.         pQ->front = (pQ->front + 1) % Q_LEN;
  52.         return true;
  53.     }
  54. }

  55. int main(void) {
  56.     QUEUE Q;
  57.     int val;

  58.     init(&Q);
  59.     en_queue(&Q, 1);
  60.     en_queue(&Q, 2);
  61.     en_queue(&Q, 3);
  62.     en_queue(&Q, 4);
  63.     en_queue(&Q, 5);
  64.     en_queue(&Q, 6);
  65.     en_queue(&Q, 7);
  66.     en_queue(&Q, 8);

  67.     traverse_queue(&Q);

  68.     if (out_queue(&Q, &val)) {
  69.         printf("出队成功,队列出队的元素是: %d\n", val);
  70.     } else {
  71.         printf("出队失败!\n");
  72.     }

  73.     traverse_queue(&Q);

  74.     free(Q.pBase);
  75.     return 0;
  76. }

阅读(4672) | 评论(0) | 转发(2) |
0

上一篇:dlopen函数详解

下一篇:udp流检测统计

给主人留下些什么吧!~~