문제
정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 여섯 가지이다.
- push X: 정수 X를 큐에 넣는 연산이다.
- pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- size: 큐에 들어있는 정수의 개수를 출력한다.
- empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
- front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
입력
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
예제 입력 1 복사
15
push 1
push 2
front
back
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
front
예제 출력 1 복사
1
2
2
0
1
2
-1
0
1
-1
0
3
첫번째 시도 ✏️
const fs = require('fs');
const filePath =
process.platform === 'linux' ? 'dev/stdin' : '../../example.txt';
const [count, ...input] = fs
.readFileSync(filePath)
.toString()
.trim()
.split('\n')
.map((v) => v.trim());
let stack = [];
let answer = [];
input.forEach((v) => {
const [cmd, val] = v.split(' ');
switch (cmd) {
case 'push':
stack.push(val);
break;
case 'pop':
answer.push(stack[0] ?? -1);
stack = stack.slice(1);
break;
case 'size':
answer.push(stack.length);
break;
case 'empty':
answer.push(stack.length === 0 ? 1 : 0);
break;
case 'front':
answer.push(stack[0] ?? '-1');
break;
case 'back':
answer.push(stack[stack.length - 1] ?? '-1');
break;
}
});
console.log(answer.join('\n'));
array stack을 만들어서 간단하게 했지만 메모리 초과로 실패했다. 아마 pop 에서 slice로 가장 앞의 요소를 제거할 때가 문제인 것 같아서 찾아보니 array.shift, array.splice와 직접 Queue를 구현한 방식의 속도 차이가 있었다.
따라서 직접 Node와 LinkedList (Single Linked List) 클래스를 만들어 다시 풀어주었다.
두번째 시도 🎉
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(data) {
const node = new Node(data);
if (this.head) {
this.tail.next = node;
} else {
this.head = node;
this.head.next = null;
}
this.tail = node;
this.length += 1;
}
pop() {
if (this.length === 0) return -1;
if (this.length === 1) {
this.tail = null;
}
const poped = this.head;
this.head = this.head.next;
this.length -= 1;
return poped.data;
}
size() {
return this.length;
}
empty() {
return this.length === 0 ? 1 : 0;
}
front() {
return this.head ? this.head.data : -1;
}
back() {
return this.tail ? this.tail.data : -1;
}
}
let answer = [];
let linkedList = new LinkedList();
input.forEach((v) => {
const [cmd, val] = v.split(' ');
switch (cmd) {
case 'push':
linkedList.push(Number(val));
break;
case 'pop':
answer.push(linkedList.pop());
break;
case 'size':
answer.push(linkedList.size());
break;
case 'empty':
answer.push(linkedList.empty());
break;
case 'front':
answer.push(linkedList.front());
break;
case 'back':
answer.push(linkedList.back());
break;
}
});
console.log(answer.join('\n'));
결과는 성공!
참고
https://www.freecodecamp.org/korean/news/implementing-a-linked-list-in-javascript/
자바스크립트로 연결 리스트를 구현하는 방법
여러분이 만약 데이터 구조를 공부하고 있다면, 연결 리스트(linked list)는 반드시 알아야 할 구조 중 하나입니다. 연결 리스트를 좀 더 이해하고 싶거나 구현하는 방법이 궁금하다면 이 게시글이
www.freecodecamp.org
https://junghyeonsu.tistory.com/243
[백준] 18258번: 큐 2 (JavaScript, NodeJS)
문제 정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오. 명령은 총 여섯 가지이다. push X: 정수 X를 큐에 넣는 연산이다. pop: 큐에서 가장 앞에 있는
junghyeonsu.tistory.com
JS 알고리즘 구현: 큐(Queue) 구현 vs Array 메서드(shift, splice) 사용했을때 속도 비교
알고리즘 코딩테스트에서 Queue 자료구조를 써야할때가 있습니다. 대표적으로 BFS를 구현할때죠.C++의 경우 STL을 통해 사용할 수 있고, Python의 경우 deque를 써서 삽입, 삭제 시 O(1)의 시간복잡도를
velog.io
'코딩테스트 > Baekjoon' 카테고리의 다른 글
[Backjoon] 창문 닫기 (0) | 2025.02.19 |
---|---|
[Baekjoon] 나는야 포켓몬 마스터 이다솜 (0) | 2025.02.10 |
[Baekjoon] 좌표 압축 (0) | 2025.01.23 |
[Baekjoon] 알고리즘 수업 - 알고리즘의 수행 시간 6 (0) | 2025.01.17 |
[Baekjoon] 알고리즘 수업 - 알고리즘의 수행 시간 5 (0) | 2025.01.16 |