본문 바로가기
웹/JS

코딩테스트를 위한 JavaScript : 연결 리스트

by 매이나 2023. 9. 19.

연결 리스트란

각 노드가 데이터와 포인터를 가지고 한 줄로 연결된 방식으로 데이터를 저장하는 자료구조이다.

javaScript에서는 파이썬과는 다르게 큐나 트리 자료구조 관련 기본 라이브러리가 없어 직접 구현해야 한다.

그리고 그 자료구조를 구현하기에 연결 리스트가 사용된다.

 

연결 리스트 구현

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  size() {
    let count = 0;
    let currentNode = this.head;
    while (currentNode) {
      count++;
      currentNode = currentNode.next;
    }
    return count;
  }

  find(value) {
    let current = this.head;
    while (current?.value !== value && current) {
      current = current.next;
    }
    return current;
  }

  append(value) {
    const newNode = new Node(value);
    if (this.head === null) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }
  }

  removeFirst() {
    const value = this.head.value;
    this.head = this.head.next;
    return value;
  }
}

 

댓글