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

Inhwan98·2023년 3월 30일
0

PTU STUDY_leetcode

목록 보기
23/24

문제

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

예제

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

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

Constraints:

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

코드

class MyQueue {
private:
    stack<int> st1, st2;
public:
    MyQueue() {

    }

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

    int pop() {
        int size = st1.size() - 1;
        
        while (size--)
        {
            st2.push(st1.top());
            st1.pop();
        }
        int popNum = st1.top();
        st1.pop();
        while (!st2.empty())
        {
            st1.push(st2.top());
            st2.pop();
        }
        return popNum;
    }

    int peek() {
        int size = st1.size() - 1;

        while (size--)
        {
            st2.push(st1.top());
            st1.pop();
        }
        int frontNum = st1.top();
        st2.push(st1.top());
        st1.pop();
        while (!st2.empty())
        {
            st1.push(st2.top());
            st2.pop();
        }
        return frontNum;
    }

    bool empty() {
        if (st1.empty()) return true;
        else 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();
 */

결과

Runtime 4 ms / Memory 7.1 MB
https://leetcode.com/problems/implement-queue-using-stacks/submissions/925093713/


https://leetcode.com/problems/implement-queue-using-stacks/

profile
코딩마스터

0개의 댓글