tariq_zaghal

Queue using linked list

Apr 30th, 2023
860
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.38 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node{
  5.     int val;
  6.     struct node* next;
  7.     struct node* rear;
  8. };
  9.  
  10.  
  11. typedef struct node* Queue;
  12.  
  13. Queue createQueue();
  14. int isEmpty(Queue Q);
  15. void enqueue(int x , Queue Q);
  16. void dequeue(Queue Q);
  17. int front(Queue Q);
  18. int frontAndDequeue(Queue Q);
  19.  
  20. int main(){
  21.  
  22.     // Queue queue1 = createQueue();
  23.  
  24.     // enqueue(13,queue1);
  25.     // enqueue(23,queue1);
  26.     // enqueue(33,queue1);
  27.     // enqueue(43,queue1);
  28.     // enqueue(53,queue1);
  29.  
  30.     // dequeue(queue1);
  31.  
  32.  
  33.     // while(!isEmpty(queue1)){
  34.     //     int x = frontAndDequeue(queue1);
  35.     //     printf("%d ",x);
  36.     // }
  37.  
  38.     // printf("\n");
  39.  
  40. }
  41.  
  42.  
  43. Queue createQueue(){
  44.     Queue Q = malloc(sizeof(struct node));
  45.     Q->next = NULL;
  46.     Q->rear = Q;
  47.  
  48.     return Q;
  49. }
  50.  
  51. int isEmpty(Queue Q){
  52.     return Q->next == NULL;
  53. }
  54.  
  55. void enqueue(int x , Queue Q){
  56.     struct node* newElem = malloc(sizeof(struct node));
  57.     newElem->val = x;
  58.     Q->rear->next = newElem;
  59.     Q->rear = Q->rear->next;
  60.     Q->rear->next = NULL;
  61.    // printf("%d\n",Q->rear->val);
  62. }
  63.  
  64. void dequeue(Queue Q){
  65.     if(!isEmpty(Q)){
  66.     Queue temp = Q->next;
  67.     Q->next = temp->next;
  68.     free(temp);
  69.    
  70.     }
  71.  
  72. }
  73.  
  74.  
  75. int front(Queue Q){
  76.    if(!isEmpty(Q))
  77.     return Q->next->val;
  78. }
  79.  
  80.  
  81. int frontAndDequeue(Queue Q){
  82.     int x = front(Q);
  83.     dequeue(Q);
  84.  
  85.     return x;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment