본문 바로가기
코딩테스트/백준

[백준10828][c++] 스택

by 신도리아 2023. 4. 16.

문제: https://www.acmicpc.net/problem/10828

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

접근:

2년 전, 자료구조 수강 당시

c로 풀어본 이력이 있었다.

c++ stack 라이브러리를 활용하니까 확실히 간결하고 편했다.

 

별다른 코드 작성 없이

stack 메소드 활용해서 작성한게 전부이고

스택 비어있을 때 "-1" 출력 조건 정도만 덧붙여 작성하면 끝

 

소스코드:

#include <iostream>
#include <stack>
using namespace std;
stack<int> s;
void push();
void pop();
void size();
void empty();
void top();
int main() {
  // ios:: sync_with_stdio(false);
  // cin.tie(NULL);
  // cout.tie(NULL);

  int n;
  cin >> n;

  for (int i = 0; i < n; i++) {
    string str = "";
    cin >> str;

    if (str == "push") {
      push();
    }
    if (str == "pop") {
      pop();
    }
    if (str == "size") {
      cout << s.size() << "\n";
    }
    if (str == "empty") {
      empty();
    }
    if (str == "top") {
      top();
    }
  }
  return 0;
}
void push() {
  int num;
  cin >> num;
  s.push(num);
}
void pop() {
  if (s.empty()) {
    cout << "-1\n";
    return;
  }
  cout << s.top() << "\n";
  s.pop();
}
void empty() {
  if (s.empty())
    cout << "1\n";
  else
    cout << "0\n";
}
void top(){
  if (s.empty()){
    cout << "-1\n";
    return;
  }
  cout << s.top() << "\n";
}