[LeetCode]큐를 이용한 스택 구현

Inhwan98·2023년 3월 30일
0

PTU STUDY_leetcode

목록 보기
22/24

문제

큐를 이용해 다음 연산을 지원하는 스택을 구현하라.

예제

  • Example 1:
Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]

Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

Constraints:

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, top, and empty.
  • All the calls to pop and top are valid.

코드

class MyStack {
private:
    queue<int> q1, q2;
public:
    MyStack() {

    }

    void push(int x) {
        q1.push(x);
    }

    int pop() {
        if (q1.empty()) return -1;
        int size = q1.size() - 1;
        int endNum = q1.back();

        while (size--)
        {
            q2.push(q1.front());
            q1.pop();
        }
        q1.pop();

        while (!q2.empty())
        {
            q1.push(q2.front());
            q2.pop();
        }
        return endNum;
    }

    int top() {
        if (!q1.empty()) return q1.back();
        else return -1;
    }

    bool empty() {
        if (q1.empty()) return true;
        else return false;
    }
};

결과

Runtime 0 ms / Memory 6.9 MB
https://leetcode.com/problems/implement-stack-using-queues/submissions/925093161/


https://leetcode.com/problems/implement-stack-using-queues/

profile
코딩마스터

0개의 댓글