您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

sqqueue.c 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "sqqueue.h"
  4. queue_t pkt_creat_sqqueue(int len)
  5. {
  6. queue_t q;
  7. if ((q = (queue_t)malloc(sizeof(struct queue))) == NULL)
  8. {
  9. printf("malloc failed!\n");
  10. return NULL;
  11. }
  12. if ((q->msg = (message_t)malloc(sizeof(struct message) * len)) == NULL)
  13. {
  14. printf("malloc failed!\n");
  15. return NULL;
  16. }
  17. q->front = q->rear = len - 1;
  18. q->len = len;
  19. return q;
  20. }
  21. int pkt_empty_sqqueue(queue_t q)
  22. {
  23. return q->front == q->rear;
  24. }
  25. int pkt_full_sqqueue(queue_t q)
  26. {
  27. return (q->rear + 1) % q->len == q->front; /* 空出一个消息位置判断为满,队列最大装len - 1个 */
  28. }
  29. int pkt_put_message_sqqueue(queue_t q, message_t m)
  30. {
  31. if (pkt_full_sqqueue(q))
  32. {
  33. printf("squeue is full!\n");
  34. return -1;
  35. }
  36. q->rear = (q->rear + 1) % q->len; /* first rear++ */
  37. q->msg[q->rear] = *m;
  38. return 0;
  39. }
  40. int pkt_take_message_sqqueue(queue_t q, message_t m)
  41. {
  42. if (pkt_empty_sqqueue(q))
  43. {
  44. printf("squeue is empty!\n");
  45. return -1;
  46. }
  47. q->front = (q->front + 1) % q->len; /* frist front++ */
  48. *m = q->msg[q->front];
  49. return 0;
  50. }
  51. int pkt_show_sqqueue(queue_t q)
  52. {
  53. int i;
  54. for (i = (q->front + 1) % q->len; i != (q->rear + 1) % q->len; i = (i + 1) % q->len)
  55. {
  56. printf("queue[%d] = %d\n", i, q->msg[i].data);
  57. }
  58. return 0;
  59. }
  60. int main(int argc, char **argv)
  61. {
  62. queue_t q;
  63. q = pkt_creat_sqqueue(10);
  64. struct message m;
  65. for (int i = 1; i <= 10; i++)
  66. {
  67. m.data = i;
  68. printf("put %d\n", m.data);
  69. pkt_put_message_sqqueue(q, &m);
  70. }
  71. while (!pkt_empty_sqqueue(q))
  72. {
  73. pkt_take_message_sqqueue(q, &m);
  74. printf("take = %d\n", m.data);
  75. }
  76. pkt_show_sqqueue(q);
  77. return 0;
  78. }