Algorithm
[c++]baekjoon 10828
denishong4.0
2021. 4. 4. 07:54
반응형
c++ stack함수들을 이용해서 풀어 본 문제입니다.
여기서 구현 시 주의 할 점 몇가지를 정리해 봤습니다.
pop() return값이 void형태이어서 출력값이 없어서 top()으로 먼저 출력 후 pop()을 호출해야 합니다.
그리고 top()호출시 stack이 비워있을 경우 호출 시 segment fault발생하므로 stack이 비워있다면 -1을 출력하도록 예외 사항을 추가해 줘야 합니다.
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
int main()
{
char input[10];
int val,count;
stack<int> s;
// input number
cin >> count;
for( int i = 0; i < count; i++ )
{
cin >> input;
if ( !strcmp("push", input) ){
cin >> val;
s.push(val);
}
else if( !strcmp(input, "pop") ){
if( !s.empty() )
{
cout << s.top() << endl;
s.pop();
}else{
cout << "-1" << endl;
}
}
else if( !strcmp(input, "size") ){
cout << s.size() << endl;
}
else if( !strcmp(input, "empty") ){
cout << s.empty() << endl;
}
else if( !strcmp(input, "top") ){
if( !s.empty() )
cout << s.top() << endl;
else
cout << "-1" << endl;
}
}
return 0;
}
반응형