정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 다섯 가지이다.
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
예제1 입력
14
push 1
push 2
top
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
top
예제1 출력
2
2
0
2
1
-1
0
1
-1
0
3
예제2 입력
7
pop
top
push 123
top
pop
top
pop
예제2 출력
-1
-1
123
123
-1
-1
10,000
으로 시간복잡도의 코스트가 높은 연산을 할때 시간초과가 날 수도 있을거라 생각했다. (stack, currentIndex)
하고, 덧셈 산술 연산을 사용하여 스택 자료구조를 우회적으로 구현하였다.console.log()
를 1만번 찍으면 시간 초과가 날것같아 answer
이라는 변수를 선언하여 공백 기준으로 입력값을 저장하고, 출력할때 answer.split(' ').join('\n')
으로 출력해주었다. const fs = require('fs');
const root = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
const [n, ...commands] = fs.readFileSync(root, 'utf8').toString().trim()
.split('\n');
console.log(solution(n, commands));
function solution(n, commands){
const stack = [];
let currentIndex = 0;
let answer = '';
for(let i = 0; i < +n; i++){
const [command, num] = commands[i].split(' ');
let result = '';
switch(command){
case 'push':
stack[currentIndex] = num;
currentIndex += 1;
break;
case 'pop':
if(currentIndex === 0) {
result = -1;
answer += result + ' ';
}
if(currentIndex > 0) {
currentIndex -= 1;
result = stack.splice(-1);
answer += result + ' ';
}
break;
case 'size':
result = currentIndex;
answer += result + ' ';
break;
case 'empty':
result = currentIndex === 0 ? 1 : 0;
answer += result + ' ';
break;
case 'top':
result = currentIndex === 0 ? -1 : stack[currentIndex - 1];
answer += result + ' ';
break;
}}
return answer.split(' ').join('\n');
}