
📅 2025-10-30
➡️ 알고리즘 배열, 스택, 큐에 대해 새롭게 알게 된 것 또는 헷갈리는 부분 정리
key/value)length 속성 제공class MyArray {
constructor() {
this.data = {};
this.length = 0;
}
// 값 추가
push(value) {
this.data[this.length] = value;
this.length++;
return this.length;
}
// 마지막 요소 제거
pop() {
if (this.length === 0) return undefined; // 비어있으면 undefined 반환
const lastIndex = this.length - 1;
const lastValue = this.data[lastIndex];
delete this.data[lastIndex];
this.length--;
return lastValue;
}
// 인덱스로 접근
get(index) {
return this.data[index];
}
// 인덱스 기반 삭제
delete(index) {
if (index < 0 || index >= this.length) return undefined;
const deletedValue = this.data[index];
// 삭제한 인덱스 이후의 요소들을 한 칸씩 앞으로 이동
for (let i = index; i < this.length - 1; i++) {
this.data[i] = this.data[i + 1];
}
delete this.data[this.length - 1];
this.length--;
return deletedValue;
}
// 이미 존재하는 인덱스의 값을 교체하는 함수
set(index, value) {
if (index < 0 || index >= this.length) return undefined;
this.data[index] = value;
console.log(this.data);
console.log(this.length);
return this.length;
}
// 특정 인덱스 위치에 값을 삽입하는 함수
insert(index, value) {
if (index < 0 || index > this.length) return undefined;
// 뒤에서부터
for (let i = this.length - 1; i >= index; i--) {
this.data[i + 1] = this.data[i];
}
this.data[index] = value;
this.length++;
console.log(this.data);
console.log(this.length);
return this.length;
}
// 배열 안에 특정 값이 존재하는지 확인하는 함수
includes(value) {
for (let i = 0; i < this.length; i++) {
if (this.data[i] === value) return true;
}
return false;
}
}
const arr = new MyArray();
push()로 데이터를 넣고, pop()으로 제거class Stack {
constructor() {
this.arr = [];
}
push(value) {
this.arr.push(value);
}
pop() {
this.arr.pop();
}
peek() {
return this.arr[this.arr.length - 1];
}
}
const stack = new Stack();
class Queue {
constructor() {
this.arr = [];
}
enqueue(value) {
this.arr.push(value);
}
dequeue() {
if (this.arr.length === 0) return undefined;
return this.arr.shift();
}
isEmpty() {
return this.arr.length === 0;
}
size() {
return this.arr.length;
}
clear() {
this.arr = [];
}
}
const queue = new Queue();