Queue using Two Stacks

  • + 1 comment

    C++20 -- My code keeps getting "Time Limit Exceeded" for many test cases and works for the rest. Could someone help me address that?

    struct Queue {
        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-device
     
        void Enqueue(int x) // to enqueue x at the end of the queue
        {
            while (!stack1.empty()) { // until stack1 is empty
                stack2.push(stack1.top()); // push element from top of stack1 into stack2
                stack1.pop(); // remove the top of stack1 to expose the next top
            }
     
            // Push x into s1, which is currently empty
            stack1.push(x);
     
            // Now take everything from stack2 and put it back in stack1
            while (!stack2.empty()) {
                stack1.push(stack2.top());
                stack2.pop();
            }
        }
        
        void Dequeue(){
            stack1.pop();
        }
     
        // Dequeue an item from the queue
        int Get_Front()
        {
            // Return top of s1
            int x = stack1.top(); // x is the top of stack1
            //stack1.pop(); // throw away top of stack1
            return x; // return the top of stack1
        }
        
    };
    
    int main(){
        Queue queue;
        int q;
        cin >> q;
        int query;
        for (int i = 0; i < q-1; i++){
            cin >> query;
            if (query == 1){
                int x;
                cin >> x;
                queue.Enqueue(x);
            }
            else if (query == 2) queue.Dequeue();
            else cout << queue.Get_Front() << endl;
        }