자료구조 - 이중 연결 리스트

박춘화·2022년 1월 7일
0

Computer Science

목록 보기
3/3
class Node {
  constructor(value) {
    this.value = value;
    this.prev = null;
    this.next = null;
  }
}

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

  isEmpty() {
    return this.head === null;
  }

  push(newNode) {
    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      let node = this.tail;
      node.next = newNode;
      newNode.prev = node;
      this.tail = newNode;
    }
  }

  pop() {
    if (!this.isEmpty()) {
      if (this.head === this.tail) {
        const tail = this.tail;

        this.head = null;
        this.tail = null;

        return tail;
      } else {
        const tail = this.tail;
        const nextTail = this.tail.prev;

        tail.prev = null;
        nextTail.next = null;
        this.tail = nextTail;

        return tail;
      }
    }
  }

  print() {
    if (!this.isEmpty()) {
      const result = [];

      let node = this.head;

      while (node) {
        result.push(node.value);
        node = node.next;
      }

      console.log(result);
    }
  }

  hasValue(value) {
    if (!this.isEmpty()) {
      let node = this.head;

      while (node) {
        if (node.value === value) {
          return true;
        }
        node = node.next;
      }

      return false;
    }
  }
  
  getLength() {
    return this.length;
  }

  popIndexOf(index) {
    if (index <= this.length) {
      let currentIndex = 1;
      let node = this.head;

      while (currentIndex !== index) {
        node = node.next;
        currentIndex += 1;
      }

      const prevNode = node.prev;

      if (this.tail === node) {
        this.tail = prevNode;
        prevNode.next = null;
      } else {
        const nextNode = node.next;
        prevNode.next = nextNode;
        nextNode.prev = prevNode;
      }

      node.prev = null;
      node.next = null;
      return node;
    }
  }
}
profile
함께 성장하는 개발자

0개의 댓글