알고리즘 풀이/백준(Boj)

백준(BOJ) 10828번 스택

100win10 2019. 8. 18. 19:36

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


문제

정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 다섯 가지이다.

  • push X: 정수 X를 스택에 넣는 연산이다.
  • pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 스택에 들어있는 정수의 개수를 출력한다.
  • empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
  • top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.



나의 풀이:


스택의 성질인 FILO 을 기억하면서 풀어주면 되겠다. top을 -1로 두고 push일때는 증가, pop일때는 감소하면서 진행해주자


STL의 stack을 사용해서 풀수도 있고 문제가 간단하기에 그냥 풀어도 된다.




코드 ( C++ )


//STL stack 사용

#include <iostream>

#include <vector>

#include <string>

#include <stack>

using namespace std;

int N;

int main()

{

cin >> N;

stack<int> st;

for (int i = 0; i < N; ++i)

{

string s;

cin >> s;

if (s == "push") {

int n;

cin >> n;

st.push(n);

}

else if (s == "pop"){

if (st.empty())

cout << -1 << "\n";

else {

cout << st.top() << "\n";

st.pop();

}

}

else if (s == "top") {

if (st.empty())

cout << -1 << "\n";

else {

cout << st.top() << "\n";

}

}

else if (s == "size") {

cout << st.size() << "\n";

}

else if (s == "empty") {

if (st.empty())

cout << 1 << "\n";

else

cout << 0 << "\n";

}

}

}




// 배열을 이용하여 풀기

/*

int main()

{

int N;

cin >> N;

int stack[MAX];

int top = -1;

for (int i = 0; i < N; ++i)

{

string s;

cin >> s;

if (s == "push") {

int n;

cin >> n;

stack[++top] = n;

}

else if (s == "top") {

if (top == -1)

cout << -1 << "\n";

else {

cout << stack[top] << "\n";

}

}

else if (s == "size") {

cout << top + 1 << "\n";

}

else if (s == "empty") {

if (top == -1)

cout << 1 << "\n";

else

cout << 0 << "\n";

}

else if (s == "pop") {

if (top == -1)

cout << -1 << "\n";

else {

cout << stack[top--] << "\n";

}


}

}

return 0;

} */