[JS] Data Structure - Stack & Queue

Fleuve·2020년 10월 25일
0

Data Structure

목록 보기
3/5
post-thumbnail

1. Stack

Stack은 한 쪽 끝에서만 자료구조를 넣고 뺄 수 있는 LIFO(Last IN First Out) 형식의 자료구조이다.
즉, 가장 최근에 스택에 추가된 데이터를 가장 먼저 삭제하는 것을 말한다.

  • Stack구현

    Stack 메서드

    • size() -현재 this.top를 반환한다. 만약 this.top가 0보다 작게 될경우 0을 리턴한다.
    • push(element) - 주어진 element를 stack에 추가합니다. 현재 this.topthis.storage의 키로 주어주고 elemet를 value로 넣어준다. 그리고 this.top를 1증가 시킨다.
    • pop() - this.storage에서 this.top를 키로가지고 있는 데이터를 제거하고 제거된 this.top의 value를 반환한다. 그리고 this.top를 1 감소 시킨다.
class Stack {
  constructor() {
    this.storage = {};
    this.top = 0;
  }

  size() {
    if (this.top < 0) {
      return 0;
    }
    return this.top;
  }

  push(element) {
    this.storage[this.top] = element;
    this.top++;
  }

  pop() {
    this.top--;
    const pop = this.storage[this.top];
    delete this.storage[this.top];
    return pop;
  }
}

module.exports = Stack;

2. Queue

Queue는 한 쪽 끝에서만 자료구조를 넣고 뺄 수 있는 LIFO(Last IN First Out) 형식의 자료구조이다.
즉, 가장 최근에 스택에 추가된 데이터를 가장 먼저 삭제하는 것을 말한다.

  • Queue 구현

    Queue 메서드

    • size() - this.rearthis.fornt를 뺀 값을 반환한다. 만약 size가 0보다 작아질 경우 0을 반환한다.
    • enqueue(element) - 현재 this.rear의 값을 this.storage의 키로 주고 element를 value로 할당한다. 그리고 this.rear을 1 증가시킨다.
    • dequeue() - 현재 this.storage에서 this.front를 key로 가지고 있는 데이터를 제거한다. 그리고 this.front를 증가 시키고 제거된 데이터를 반환한다.
class Queue {
  constructor() {
    this.storage = {};
    this.front = 0;
    this.rear = 0;
  }

  size() {
    const size = this.rear - this.front;
    if (size < 0) {
      return 0;
    }
    return size;
  }

  enqueue(element) {
    this.storage[this.rear] = element;
    this.rear++;
  }

  dequeue() {
    const removeItem = this.storage[this.front];
    delete this.storage[this.front];
    this.front++;
    return removeItem;
  }
}

module.exports = Queue;

0개의 댓글