You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

linkqueue.c 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "linkqueue.h"
  4. linkqueue_t pkt_creat_linkqueue(void)
  5. {
  6. linkqueue_t q;
  7. if ((q = (linkqueue_t)malloc(sizeof(struct linkqueue))) == NULL) /* malloc queue */
  8. {
  9. printf("malloc filed!\n");
  10. return NULL;
  11. }
  12. queue_node_t h;
  13. if ((h = (queue_node_t)malloc(sizeof(struct queue_node))) == NULL) /* malloc head node */
  14. {
  15. printf("malloc filed!\n");
  16. return NULL;
  17. }
  18. h->next = NULL;
  19. q->front = q->rear = h;
  20. return q;
  21. }
  22. int pkt_empty_linkqueue(linkqueue_t q)
  23. {
  24. return q->front->next == NULL;
  25. }
  26. int pkt_put_message_linkqueue(linkqueue_t q, message_t m)
  27. {
  28. /* linkqueue not have sapce limit */
  29. queue_node_t n;
  30. if ((n = (queue_node_t)malloc(sizeof(struct queue_node))) == NULL)
  31. {
  32. printf("malloc filed!\n");
  33. return -1;
  34. }
  35. n->msg = *m;
  36. n->next = q->rear->next;
  37. q->rear->next = n;
  38. q->rear = n; /* move q->rear to new node, is tail */
  39. // printf("put queue node = %p data = %p\n", q->rear->next, n->msg.data);
  40. // ptk_show_linkqueue(q);
  41. return 0;
  42. }
  43. int pkt_take_message_linkqueue(linkqueue_t q, message_t m)
  44. {
  45. if (pkt_empty_linkqueue(q))
  46. {
  47. printf("linkqueue is empty!\n");
  48. return -1;
  49. }
  50. // printf("take queue node = %p\n", q->front->next);
  51. *m = q->front->next->msg;
  52. queue_node_t del = q->front->next;
  53. q->front->next = del->next; /* q->front is alwasy in head, did not move */
  54. free(del);
  55. return 0;
  56. }
  57. void ptk_show_linkqueue(linkqueue_t q)
  58. {
  59. queue_node_t m;
  60. for (m = q->front->next; m != NULL; m = m->next)
  61. {
  62. printf("linkqueue = %p\n", m->msg.data);
  63. }
  64. }
  65. #if 0
  66. int main(int argc, char *argv[])
  67. {
  68. linkqueue_t q;
  69. struct message m;
  70. q = pkt_creat_linkqueue();
  71. for (int i = 1; i <= 10; i++)
  72. {
  73. m.data = i;
  74. printf("put = %d\n", m.data);
  75. pkt_put_message_linkqueue(q, &m);
  76. }
  77. ptk_show_linkqueue(q);
  78. while (!pkt_empty_linkqueue(q))
  79. {
  80. pkt_take_message_linkqueue(q, &m);
  81. printf("take = %d\n", m.data);
  82. }
  83. pkt_take_message_linkqueue(q, &m);
  84. return 0;
  85. }
  86. #endif