Leetcode - 232. Implement Queue using Stacks

숲사람·2023년 8월 3일
0

멘타트 훈련

목록 보기
221/237

문제

아래와 같은 queue의 동작을 두개의 stack만 이용해서 구현하라. stack은 push/pop/top/size/empty 메소드를 사용할 수 있다.

Implement the MyQueue class:

void push(int x) Pushes element x to the back of the queue.
int pop() Removes the element from the front of the queue and returns it.
int peek() Returns the element at the front of the queue.
boolean empty() Returns true if the queue is empty, false otherwise.

아이디어

  • push는 첫번째 스택에 push한다. O(1)
  • pop/peek를 할때는 첫번째 스택에서 요소를 모두 두번째 스택으로 push한다. 그러면 가장 top이 queue의 top이 된다. O(n)

풀이

class MyQueue {
public:
    stack<int> first, second;
    MyQueue() {
        
    }
    
    void push(int x) {
        first.push(x);
    }
    
    int pop() {
        while (first.size()) {
            second.push(first.top());
            first.pop();
        }
        int ret = second.top();
        second.pop();
        while (second.size()) {
            first.push(second.top());
            second.pop();
        }
        return ret;
    }
    
    int peek() {
        while (first.size()) {
            second.push(first.top());
            first.pop();
        }
        int ret = second.top();
        while (second.size()) {
            first.push(second.top());
            second.pop();
        }
        return ret;
    }
    
    bool empty() {
        if (first.size() == 0)
            return true;
        return false;
    }
};

/**
 * 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();
 */
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글