99클럽 코테스터디 6기 04, 05일차 TIL

glory_young·2025년 4월 6일
post-thumbnail

문제접근

문제 :
LeetCode 232. Implement Queue using Stacks
(https://leetcode.com/problems/implement-queue-using-stacks/submissions/1599103736/)
LeetCode 225. Implement Stack using Queues (https://leetcode.com/problems/implement-stack-using-queues/description/)

  1. stack과 queue에 대한 이해 필요
    자료구조 stack, queue

제출코드

#include <stack>

class MyQueue {
private:
stack<int> s_main;
stack<int> s_sub;

public:
    MyQueue() {
        
    }
    
    void push(int x) {
        s_main.push(x);
    }
    
    int pop() {
        while (s_main.size() > 1) {
            s_sub.push(s_main.top());
            s_main.pop();
        }
        int result = s_main.top();
        s_main.pop();
        while(!s_sub.empty()) {
            s_main.push(s_sub.top());
            s_sub.pop();
        }
        
        return result;
    }
    
    int peek() {
        while (s_main.size() > 1) {
            s_sub.push(s_main.top());
            s_main.pop();
        }
        int result = s_main.top();

        while(!s_sub.empty()) {
            s_main.push(s_sub.top());
            s_sub.pop();
        }
        
        return result;
    }
    
    bool empty() {
        return s_main.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();
 */
#include <queue>

class MyStack {
private:
    queue<int> q1;
    queue<int> q2;

public:
    MyStack() {
        
    }
    
    void push(int x) {
        q1.push(x);
    }
    
    int pop() {
        while(q1.size()>1) {
            q2.push(q1.front());
            q1.pop();
        }
        int result = q1.front();
        q1.pop();
        while(!q2.empty()) {
            q1.push(q2.front());
            q2.pop();
        }
        return result;
        
    }
    
    int top() {
        while(q1.size()>1) {
            q2.push(q1.front());
            q1.pop();
        }
        int result = q1.front();
        q2.push(result);
        q1.pop();
        while(!q2.empty()) {
            q1.push(q2.front());
            q2.pop();
        }
        return result;
    }
    
    bool empty() {
        return q1.empty();
    }
};

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

오늘의 회고

쉬는 기간동안 배운 것들을 많이 까먹었다. 더 많은 공부가 필요할 것 같다.

0개의 댓글