JS' 공부흔적

[JavaScript] Deque 구현 본문

JavaScript

[JavaScript] Deque 구현

이준수 2023. 4. 28. 10:57
class Node {
  constructor(d) {
    this.data = d;
    this.next = null;
    this.prev = null;
  }
}

class Deque {
  constructor() {
    this.head = null;
    this.tail = null;
    this.size = 0;
  }

  push_front(d) {
    const node = new Node(d);
    if (this.empty()) {
      this.tail = node;
    } else {
      node.next = this.head;
      this.head.prev = node;
    }
    this.head = node;
    this.size++;
  }

  push_back(d) {
    const node = new Node(d);
    if (this.empty()) {
      this.head = node;
    } else {
      this.tail.next = node;
      node.prev = this.tail;
    }
    this.tail = node;
    this.size++;
  }

  pop_front() {
    if (this.empty()) return -1;
    const d = this.head.data;
    this.head = this.head.next;
    if (this.size === 1) this.head = null;
    else this.head.prev = null;
    this.size--;
    return d;
  }

  pop_back() {
    if (this.empty()) return -1;
    const d = this.tail.data;
    this.tail = this.tail.prev;
    if (this.size === 1) this.tail = null;
    else this.tail.next = null;
    this.size--;
    return d;
  }

  empty() {
    return this.size === 0 ? 1 : 0;
  }

  front() {
    if (this.empty()) return -1;
    return this.head.data;
  }

  back() {
    if (this.empty()) return -1;
    return this.tail.data;
  }
}
728x90
반응형