Menu
Coddy logo textTech

Practice #4

Coddy의 스택 - 자료구조 시리즈 #1 코스 레슨 — 13개 중 12번째.

최소/최대 스택을 만들어 봅시다!

challenge icon

챌린지

쉬움

이전의 Stack 클래스에 다음 두 가지 함수를 추가하세요:

  • min - 현재 스택에 있는 숫자 중 최솟값을 반환합니다.
  • max - 현재 스택에 있는 숫자 중 최댓값을 반환합니다.

보너스:push 또는 pop 연산 시 스택의 모든 요소를 반복해서 확인하지 않도록 시도해 보세요.

직접 해보기

#include <iostream>
#include <sstream>
#include <string>
#include "stack.h"

int main() {
    Stack stack;
    std::string line;
    while (std::getline(std::cin, line)) {
        std::istringstream iss(line);
        std::string cmd;
        if (!(iss >> cmd)) continue;
        if (cmd == "push") {
            int x; iss >> x; stack.push(x);
        } else if (cmd == "pop") {
            std::cout << stack.pop() << std::endl;
        } else if (cmd == "top") {
            std::cout << stack.top() << std::endl;
        } else if (cmd == "size") {
            std::cout << stack.size() << std::endl;
        } else if (cmd == "min") {
            std::cout << stack.min() << std::endl;
        } else if (cmd == "max") {
            std::cout << stack.max() << std::endl;
        }
    }
    return 0;
}

스택 - 자료구조 시리즈 #1의 모든 레슨