fork download
  1. /******************************************************************************
  2.  
  3.   Online C Compiler.
  4.   Code, Compile, Run and Debug C program online.
  5. Write your code in this editor and press "Run" button to compile and execute it.
  6.  
  7. *******************************************************************************/
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. struct Node {
  11. int data;
  12. struct Node* next;
  13. };
  14. struct Queue {
  15. struct Node *front, *rear;
  16. };
  17. struct Node* createNode(int newdata);
  18. void enQueue(struct Queue* q, int value) {
  19. struct Node* newNode = createNode(value);
  20. if (q->front == NULL)
  21. q->front = newNode;
  22. else
  23. q->rear->next = newNode;
  24. q->rear = newNode;
  25. q->rear->next = q->front;
  26. }
  27. int deQueue(struct Queue* q) {
  28. if (q->front == NULL) {
  29. return -1;
  30. }
  31. int value;
  32. if (q->front == q->rear) {
  33. value = q->front->data;
  34. free(q->front);
  35. q->front = q->rear = NULL;
  36. } else {
  37. struct Node* temp = q->front;
  38. value = temp->data;
  39. q->front = q->front->next;
  40. q->rear->next = q->front;
  41. free(temp);
  42. }
  43. return value;
  44. }
  45. void printQueue(struct Queue* q) {
  46. if (q->front == NULL) return;
  47. struct Node* curr = q->front;
  48. do {
  49. printf("%d ", curr->data);
  50. curr = curr->next;
  51. } while (curr != q->front);
  52. printf("\n");
  53. }
  54. int front(struct Queue* q) {
  55. struct Node* front = q->front;
  56. if (front == NULL) {
  57. return -1;
  58. }
  59. return front->data;
  60. }
  61. int rear(struct Queue* q) {
  62. struct Node* rear = q->rear;
  63. if (rear == NULL) {
  64. return -1;
  65. }
  66. return rear->data;
  67. }
  68. struct Queue* createQueue() {
  69. struct Queue* q =
  70. (struct Queue*)malloc(sizeof(struct Queue));
  71. q->front = q->rear = NULL;
  72. return q;
  73. }
  74. struct Node* createNode(int newdata) {
  75. struct Node* newnode
  76. = (struct Node*)malloc(sizeof(struct Node));
  77. newnode->data = newdata;
  78. newnode->next = NULL;
  79. return newnode;
  80. }
  81. int main() {
  82. struct Queue* q = createQueue();
  83. enQueue(q, 14);
  84. enQueue(q, 22);
  85. enQueue(q, 6);
  86. enQueue(q, 20);
  87. printf("Front value: %d\n", front(q));
  88. printf("Rear value: %d\n", rear(q));
  89. printQueue(q);
  90. printf("Deleted value = %d\n", deQueue(q));
  91. printf("Deleted value = %d\n", deQueue(q));
  92. printQueue(q);
  93. return 0;
  94. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
Front value: 14
Rear value: 20
14 22 6 20 
Deleted value = 14
Deleted value = 22
6 20