Implement Queue using Stacks

ㅋㅋ·2022년 12월 16일
0

알고리즘-leetcode

목록 보기
71/135

제목 그대로 stack을 사용하여 queue를 구현하는 문제

단순히 두 개의 stack을 사용하는 방법이 아닌

1개만 사용하는 방법이 있을까하여 생각해봤는데

방법이 떠오르지 않아 다른 사람이 한 걸 참고하였다.

class MyQueue {
public:
    stack<int> _stack{};

    MyQueue() {
        
    }
    
    void push(int x) {
        if (_stack.empty())
        {
            _stack.push(x);
        }
        else
        {
            int temp = _stack.top();
            _stack.pop();
            push(x);
            _stack.push(temp);
        }
    }
    
    int pop() {
        int result{_stack.top()};
        _stack.pop();
        return result;
    }
    
    int peek() {
        return _stack.top();
    }
    
    bool empty() {
        return _stack.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

0개의 댓글