10828번 - 스택
2022. 4. 13. 16:09ㆍ백준/C++
정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 다섯 가지이다.
- push X: 정수 X를 스택에 넣는 연산이다.
- pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- size: 스택에 들어있는 정수의 개수를 출력한다.
- empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
- top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
#include <iostream>
#define INT_MAX 2147483647
using namespace std;
// push X: 정수 X를 스택에 넣는 연산이다.
// pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
// size: 스택에 들어있는 정수의 개수를 출력한다.
// empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
// top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
void push(int *stack, int length, int num);
void pop(int *stack, int length);
void size(int *stack, int length);
int empty(int *stack, int length);
void top(int *stack, int length);
int main(void)
{
int repeat;
cin>>repeat;
int stack[repeat];
for(int i = 0; i<repeat;i++)
stack[i] = INT_MAX; //배열 초기화
int sLength = repeat-1; //배열 길이 얻음.
//= sizeof(stack)/sizeof(stack[0]);
while(repeat--)
{
string command;
cin>>command;
if(command == "push")
{
int commandNum;
cin>>commandNum;
push(stack, sLength, commandNum);
}
else if(command == "pop")
pop(stack, sLength);
else if(command == "size")
size(stack, sLength);
else if(command == "empty")
empty(stack, sLength);
else if(command == "top")
top(stack, sLength);
}
return 0;
}
void push(int *stack, int length, int num)
{
for (int i = 0; i<length; i++)
{
int element = *(stack + i);
if(element == INT_MAX)
{
*(stack + i) = num;
break;
}
}
}
void pop(int *stack, int length)
{
if(*stack == INT_MAX)
{
cout<<-1<<endl;
}
else
{
int popNum;
for(int i = 0; i<length; i++)
{
int element = *(stack + i);
if(element == INT_MAX)
{
popNum = *(stack + i - 1);
*(stack + i - 1) = INT_MAX;
break;
}
}
cout<<popNum<<endl;
}
}
void size(int *stack, int length)
{
int size=0;
for(int i = 0; i<length; i++)
{
int element = *(stack + i);
if(element == INT_MAX)
break;
size++;
}
cout<<size<<endl;
}
int empty(int *stack, int length)
{
if(*stack == INT_MAX)
{
cout<<1<<endl; return 1;
}
else
{
cout<<0<<endl; return 0;
}
}
void top(int *stack, int length)
{
if(*stack == INT_MAX)
{
cout<<-1<<endl;
}
else
{
int popNum;
for(int i = 0; i<length; i++)
{
int element = *(stack + i);
if(element == INT_MAX)
{
popNum = *(stack + i - 1);
break;
}
}
cout<<popNum<<endl;
}
}
문제를 풀고 채점 해보니 이럴수가.
정확히 1년전에 같은 문제를 시도했던 것이 발견되었다.
매우 흥미로웠다.
'백준 > C++' 카테고리의 다른 글
9012번 - 괄호 (0) | 2022.04.22 |
---|---|
10773번 - 제로 (0) | 2022.04.22 |
15596번 - 정수 N개의 합 (0) | 2022.04.14 |
10818번 - 최소, 최대 (0) | 2022.04.14 |
2750번 - 수 정렬하기 (0) | 2022.04.13 |