We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
C++20 -- My code keeps getting "Time Limit Exceeded" for many test cases and works for the rest. Could someone help me address that?
structQueue{stack<int>stack1,stack2;// we will use these two stacks; stack1 is where we will store and pop from, stack2 is used just as a transfer-devicevoidEnqueue(intx)// to enqueue x at the end of the queue{while(!stack1.empty()){// until stack1 is emptystack2.push(stack1.top());// push element from top of stack1 into stack2stack1.pop();// remove the top of stack1 to expose the next top}// Push x into s1, which is currently emptystack1.push(x);// Now take everything from stack2 and put it back in stack1while(!stack2.empty()){stack1.push(stack2.top());stack2.pop();}}voidDequeue(){stack1.pop();}// Dequeue an item from the queueintGet_Front(){// Return top of s1intx=stack1.top();// x is the top of stack1//stack1.pop(); // throw away top of stack1returnx;// return the top of stack1}};intmain(){Queuequeue;intq;cin>>q;intquery;for(inti=0;i<q-1;i++){cin>>query;if(query==1){intx;cin>>x;queue.Enqueue(x);}elseif(query==2)queue.Dequeue();elsecout<<queue.Get_Front()<<endl;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Queue using Two Stacks
You are viewing a single comment's thread. Return to all comments →
C++20 -- My code keeps getting "Time Limit Exceeded" for many test cases and works for the rest. Could someone help me address that?