Advertisement
Eternoseeker

Queue basic code, enqueue, dequeue

Nov 15th, 2022 (edited)
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | Source Code | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. struct node{
  5.     int data;
  6.     node *next;
  7. };
  8.  
  9. class queue{
  10.     node *front;
  11.     node *rear;
  12. public:
  13.     queue(){
  14.         front = rear = NULL;
  15.     }
  16.  
  17.     bool isEmpty(){
  18.         if(rear == NULL){
  19.             return true;
  20.         }
  21.         else{
  22.             return false;
  23.         }
  24.     }
  25.  
  26.     void enqueue(int v){
  27.         node *t = new node;
  28.         t -> data = v;
  29.         t -> next = NULL;
  30.         //If queue is empty, new node is front and rear both
  31.         if(rear == NULL){
  32.             front = t;
  33.             rear = t;
  34.             return;
  35.         }
  36.         //Add new node at end of the queue
  37.         rear -> next = t;
  38.         rear = t;
  39.     }
  40.  
  41.     int dequeue(){
  42.         if(front == NULL){
  43.             //cout << "Queue is empty" << endl;
  44.             return -1;
  45.         }
  46.         //Store previous front and move front one node ahead
  47.         node *t = front;
  48.         front = front -> next;
  49.         //If front becomes NULL, change rear as NULL too
  50.         if(front == NULL){
  51.             rear == NULL;
  52.         }
  53.         int val = t -> data;
  54.         free(t);
  55.         return val;
  56.     }
  57.  
  58.     void display(){
  59.             node *t=front;
  60.             while(t!=NULL){
  61.                 cout << t->data <<" -> ";
  62.                 t=t->next;
  63.             }
  64.             cout<<"NULL\n";
  65.         }
  66. };
  67.  
  68. int main(){
  69.     queue q;
  70.     int ch = 10;
  71.     while(ch != 0){
  72.         cout << "Enter your choice" << endl;
  73.         cout << "1: Enqueue element" << endl;
  74.         cout << "2: Dequeue element" << endl;
  75.         cout << "0: Exit" << endl;
  76.         cin >> ch;
  77.         switch(ch){
  78.         case 1:
  79.             int value;
  80.             cout << "Enter value: " << endl;
  81.             cin >> value;
  82.             q.enqueue(value);
  83.             q.display();
  84.             break;
  85.         case 2:
  86.             cout << "The dequeued element is: " << q.dequeue() << endl;
  87.             q.display();
  88.             break;
  89.         }
  90.     }
  91.     return 0;
  92. }
  93.  
Tags: snippets
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement