tampurus

3.2 Dynamic Queue

Dec 8th, 2021 (edited)
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. int Q_size = 0; // dynamic size of queue
  4. struct Node{
  5.     int value;
  6.     struct Node *next;
  7. };
  8. typedef struct Node Node;
  9. struct Node *head = NULL;
  10.  
  11. void Insertion(int ele){
  12.     Node *temp = ( Node*) ( malloc(sizeof(Node) ) );
  13.     if( temp == NULL){
  14.         printf("\nmemory is not allocated");
  15.         return;
  16.     }
  17.     temp->value = ele;
  18.     if(Q_size==0){
  19.         temp->next = head;
  20.         head = temp;
  21.     }
  22.     else{
  23.         struct Node *ptr = head;
  24.         int point = Q_size-1;
  25.         while(point--){
  26.             ptr = ptr->next;
  27.         }
  28.         temp->next = ptr->next;
  29.         ptr->next = temp;
  30.     }
  31.     Q_size++;
  32. }
  33. void Deletion(){
  34.     if(head == NULL){
  35.         printf("\nQueue is empty");
  36.         return;
  37.     }
  38.     Node* dele = head;
  39.     head = head->next;
  40.     free(dele);
  41.     Q_size--;
  42. }
  43. void Print(){
  44.     Node *ptr  = head;
  45.     while(ptr != NULL){
  46.         printf("%d ",ptr->value);
  47.         ptr = ptr->next;
  48.     }
  49. }
  50. int main()
  51. {
  52.     int choice,ele,key;
  53.     while(1){
  54.         printf("\n1 for insertion\n2 for deletion\nany to key just print the queue\n");
  55.         scanf("%d",&choice);
  56.         if(choice == 1){
  57.             printf("\nEnter the element ");
  58.             scanf("%d",&ele);
  59.             Insertion(ele);
  60.         }
  61.         else if (choice == 2){
  62.             Deletion();
  63.         }
  64.         else Print();
  65.         printf("\n1 to repeat and any key to exit ");
  66.         scanf("%d",&key);
  67.         if(key != 1) break;
  68.     }
  69.     return 0;
  70. }
Add Comment
Please, Sign In to add comment