jayati

mplement Queue using Linked List

Oct 11th, 2023
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. struct QueueNode
  6. {
  7.     int data;
  8.     QueueNode *next;
  9.     QueueNode(int a)
  10.     {
  11.         data = a;
  12.         next = NULL;
  13.     }
  14. };
  15.  
  16. struct MyQueue {
  17.     QueueNode *front;
  18.     QueueNode *rear;
  19.     void push(int);
  20.     int pop();
  21.     MyQueue() {front = rear = NULL;}
  22. };
  23.  
  24.  
  25.  
  26. int main()
  27. {
  28.     int T;
  29.     cin>>T;
  30.     while(T--)
  31.     {
  32.         MyQueue *sq = new MyQueue();
  33.  
  34.         int Q;
  35.         cin>>Q;
  36.         while(Q--){
  37.         int QueryType=0;
  38.         cin>>QueryType;
  39.         if(QueryType==1)
  40.         {
  41.             int a;
  42.             cin>>a;
  43.             sq->push(a);
  44.         }else if(QueryType==2){
  45.             cout<<sq->pop()<<" ";
  46.  
  47.         }
  48.         }
  49.         cout<<endl;
  50.     }
  51.     }
  52.  
  53. // } Driver Code Ends
  54.  
  55.  
  56. /* Structure of a node in Queue
  57. struct QueueNode
  58. {
  59.     int data;
  60.     QueueNode *next;
  61.     QueueNode(int a)
  62.     {
  63.         data = a;
  64.         next = NULL;
  65.     }
  66. };
  67.  
  68. And structure of MyQueue
  69. struct MyQueue {
  70.     QueueNode *front;
  71.     QueueNode *rear;
  72.     void push(int);
  73.     int pop();
  74.     MyQueue() {front = rear = NULL;}
  75. }; */
  76.  
  77. //Function to push an element into the queue.
  78. void MyQueue:: push(int x)
  79. {
  80.         // Your Code
  81.         if(front==NULL && rear==NULL)
  82.        
  83.         {
  84.             QueueNode* newnode=new QueueNode(x);
  85.             front=newnode;
  86.             rear=newnode->next;
  87.         }
  88.         else
  89.         {
  90.             QueueNode* tmp=front;
  91.             while(tmp->next!=rear)
  92.             {
  93.                 tmp=tmp->next;
  94.             }
  95.             QueueNode* newnode=new QueueNode(x);
  96.             tmp->next= newnode;
  97.             newnode->next=rear;
  98.         }
  99.        
  100. }
  101.  
  102. //Function to pop front element from the queue.
  103. int MyQueue :: pop()
  104. {
  105.         // Your Code  
  106.         int ans=-1;
  107.         if(front==NULL)
  108.         {
  109.             return -1;
  110.         }
  111.         else
  112.         {
  113.             QueueNode* tmp=front;
  114.             ans=tmp->data;
  115.             front=front->next;
  116.             delete(tmp);
  117.         }
  118.         return ans;
  119.        
  120. }
  121.  
Advertisement
Add Comment
Please, Sign In to add comment