자료구조 - 스택(Stack)/큐(Queue)

시디·2022년 1월 12일
0

자료구조

목록 보기
2/4

Stack
stack은 ‘쌓다’라는 뜻을 가지고 있으며 접시를 쌓아 놓은 형태와 비슷한 자료구조
stack은 가장 나중에 들어간 자료가 가장 먼저 나오는 LIFO(Last In First Out)형태의 자료구조이다.

  • stack 사용 예) 웹브라우저의 뒤로 가기, 앞으로 가기

✅ Stack 용어

  • push : 맨 위로 요소 추가
  • pop : 맨 위의 요소 꺼내기

✅ JavaScript로 Stack 구현

class Stack {
    constructor() {
      this.storage = {};
      this.top = 0;
    }
  
    size() {
      return this.top;
    }

    push(element) {
      this.storage[this.top] = element;
      this.top += 1;
    }
      
    pop() {
      if (this.top===0) {
        return;
      }
      const pointer = this.top-1;
      const result = this.storage[pointer];
      delete this.storage[pointer];
      this.top -= 1;
      
      return result;
    }
  }

Queue
queue는 ‘줄서서 기다리다’라는 뜻을 가지고 있으며 줄을 서서 기다리는 형태와 비슷한 자료구조
queue는 가장 먼저 들어간 자료가 가장 먼저 나오는 FIFO(First In First Out)형태의 자료구조이다.

  • queue 사용 예) 프린터의 인쇄 작업, 버퍼(각 장치 사이에 존재하는 속도 차이 극복을 위한 임시 기억 장치)

✅ Queue 용어

  • Front : Queue의 맨 앞
  • Rear : Queue의 맨 뒤
  • EnQueue : 맨 뒤로 데이터 추가
  • DeQueue : 맨 앞의 데이터 추출

✅ JavaScript로 Queue 구현

class Queue {class Queue{
    constructor(){
        this.queue = [];
        this.front = 0;
        this.rear = 0;
    }

    enqueue(value){
        this.queue[this.rear++] = value;
    }

    dequeue(){
        const value = this.queue[this.front];
        delete this.queue[this.front];
        this.front += 1;
        return value;
    }

    peek(){
        return this.queue[this.front];
    }

    size(){
        return this.rear - this.front;
    }
}
profile
콰삭칩을 그리워하는 개발자 입니다.

0개의 댓글