☁️ goormTIL | 알고리즘 #36

매루·2025년 10월 30일

goormTIL

목록 보기
34/67
post-thumbnail

📅 2025-10-30

➡️ 알고리즘 배열, 스택, 큐에 대해 새롭게 알게 된 것 또는 헷갈리는 부분 정리


🔎 학습 리마인드

📌 배열 (Array)

  • 같은 종류의 데이터를 순서대로 저장하는 구조

💡 특징

  • 순서가 있음
    • 삽입된 순서대로 저장
  • 인덱스 기반 접근
    • 각 요소는 0부터 시작하는 인덱스로 접근 가능
  • 동적 크기
    • JS 배열은 필요에 따라 크기 변경 가능
  • JS 배열은 내부적으로 객체처럼 동작 (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();

📌 스택 (Stack)

  • Last In First Out (LIFO) → 마지막에 들어간 데이터가 가장 먼저 나옴
  • push()로 데이터를 넣고, pop()으로 제거
  • 실제 사용 예시
    • 실행 취소
    • 웹브라우저 History

💡 특징

  • 삽입/삭제는 스택의 끝에서만 가능
  • 스택의 마지막 요소만 읽기 가능

💡 구현해보기

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();

📌 큐 (Queue)

  • First In, First Out(FIFO) → 먼저 들어온 데이터가 먼저 나감
  • 실제 사용 예시
    • 메시지 큐
    • 비동기 작업 순서처리
    • 프린터 인쇄 대기열

💡 특징

  • 삽입은 뒤에서, 삭제는 앞에서

💡 구현해보기

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();

0개의 댓글