Skip to content

Latest commit

 

History

History
69 lines (56 loc) · 1.08 KB

Implement-Queue-using-stacks.md

File metadata and controls

69 lines (56 loc) · 1.08 KB

Implement Queue using Stacks

Question

My Solution:

class MyQueue {

    stack<int> in, out;

public:

    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        int temp = peek();
        out.pop();
        return temp;
    }
    
    int peek() {
        if(out.empty()) {
            while(in.size()) {
                out.push(in.top());
                in.pop();
            }
        }
        return out.top();
    }
    
    bool empty() {
        return in.empty() && out.empty();
    }
};

Amortized Solution:

class MyQueue {
    stack<int> in, out;
public:

    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        int temp = peek();
        out.pop();
        return temp;
    }
    
    int peek() {
        if(out.empty()) {
            while(in.size()) {
                out.push(in.top());
                in.pop();
            }
        }
        return out.top();
    }
    
    bool empty() {
        return in.empty() && out.empty();
    }
};