spacepaste

  1.  
  2. $ cat new.c
  3. #include <stdbool.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #define pp(x) printf("%s = %p\n", #x, x);
  8. #define pi(x) printf("%s = %d\n", #x, x);
  9. #define pc(x) printf("%s = %c\n", #x, x);
  10. // A C program to demonstrate linked list based implementation of queue
  11. // A linked list (LL) node to store a queue entry
  12. int index_start = -1;
  13. int ref_start = 0;
  14. struct QNode
  15. {
  16. int index;
  17. int ref;
  18. struct QNode *next;
  19. };
  20. // The queue, front stores the front node of LL and rear stores ths
  21. // last node of LL
  22. struct Queue
  23. {
  24. struct QNode *front, *rear;
  25. };
  26. // A utility function to create a new linked list node.
  27. struct QNode* newNode(void)
  28. {
  29. struct QNode *temp = (struct QNode*)malloc(sizeof(struct QNode));
  30. temp->index = index_start++;
  31. temp->ref = ref_start++;
  32. temp->next = NULL;
  33. return temp;
  34. }
  35. // A utility function to create an empty queue
  36. struct Queue *createQueue()
  37. {
  38. struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue));
  39. q->front = q->rear = NULL;
  40. return q;
  41. }
  42. void store_asm(struct Queue *q)
  43. {
  44. // Create a new LL node
  45. struct QNode *temp = newNode();
  46. // If queue is empty, then new node is front and rear both
  47. if (q->rear == NULL)
  48. {
  49. q->front = q->rear = temp;
  50. return;
  51. }
  52. // Add the new node at the end of queue and change rear
  53. q->rear->next = temp;
  54. q->rear = temp;
  55. }
  56. struct QNode * load_asm(struct Queue **q)
  57. {
  58. // If queue is empty, return NULL.
  59. if ((q) == NULL) return NULL;
  60. if ((*q) == NULL) return NULL;
  61. if ((*q)->front == NULL)
  62. return NULL;
  63. // Store previous front and move front one node ahead
  64. struct QNode *temp = (*q)->front;
  65. (*q)->front = (*q)->front->next;
  66. // If front becomes NULL, then change rear also as NULL
  67. if ((*q)->front == NULL)
  68. (*q)->rear = NULL;
  69. return temp;
  70. }
  71. int queue_add(struct Queue **q) {
  72. if (!(*q)) (*q) = createQueue();
  73. store_asm((*q));
  74. return 0;
  75. }
  76. struct Queue * list = NULL;
  77. int main(void) {
  78. index_start = 0;
  79. ref_start = 1;
  80. queue_add(&list);
  81. queue_add(&list);
  82. queue_add(&list);
  83. struct QNode * p = list->front;
  84. while(p) {
  85. printf("%d -> %d\n", p->index, p->ref);
  86. p = p->next;
  87. }
  88. puts("NULL");
  89. return 0;
  90. }
  91. $ gcc new.c -o new
  92. $ ./new
  93. 0 -> 1
  94. 1 -> 2
  95. 2 -> 3
  96. NULL
  97.