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. struct QNode
  13. {
  14. int data;
  15. struct QNode *next;
  16. };
  17. // The queue, front stores the front node of LL and rear stores ths
  18. // last node of LL
  19. struct Queue
  20. {
  21. struct QNode *front, *rear;
  22. };
  23. // A utility function to create a new linked list node.
  24. struct QNode* newNode(int d)
  25. {
  26. struct QNode *temp = (struct QNode*)malloc(sizeof(struct QNode));
  27. temp->data = d;
  28. temp->next = NULL;
  29. return temp;
  30. }
  31. // A utility function to create an empty queue
  32. struct Queue *createQueue()
  33. {
  34. struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue));
  35. q->front = q->rear = NULL;
  36. return q;
  37. }
  38. void store_asm(struct Queue *q, int data)
  39. {
  40. // Create a new LL node
  41. struct QNode *temp = newNode(data);
  42. // If queue is empty, then new node is front and rear both
  43. if (q->rear == NULL)
  44. {
  45. q->front = q->rear = temp;
  46. return;
  47. }
  48. // Add the new node at the end of queue and change rear
  49. q->rear->next = temp;
  50. q->rear = temp;
  51. }
  52. struct QNode * load_asm(struct Queue **q)
  53. {
  54. // If queue is empty, return NULL.
  55. if ((q) == NULL) return NULL;
  56. if ((*q) == NULL) return NULL;
  57. if ((*q)->front == NULL)
  58. return NULL;
  59. // Store previous front and move front one node ahead
  60. struct QNode *temp = (*q)->front;
  61. (*q)->front = (*q)->front->next;
  62. // If front becomes NULL, then change rear also as NULL
  63. if ((*q)->front == NULL)
  64. (*q)->rear = NULL;
  65. return temp;
  66. }
  67. int queue_add(struct Queue **q, int data) {
  68. if (!(*q)) (*q) = createQueue();
  69. store_asm((*q), data);
  70. return 0;
  71. }
  72. struct Queue * list = NULL;
  73. int main(void) {
  74. queue_add(&list, 1);
  75. queue_add(&list, 2);
  76. queue_add(&list, 3);
  77. struct QNode * p = list->front;
  78. while(p) {
  79. printf("%d -> ", p->data);
  80. p = p->next;
  81. }
  82. puts("NULL");
  83. return 0;
  84. }
  85. $ gcc new.c -o new
  86. $ ./new
  87. 1 -> 2 -> 3 -> NULL
  88.