본문 바로가기
codes/자료구조

[Queue] 구현

by Mia_ 2023. 1. 15.
class Queue {
  constructor() {
    this.storage = {};
    this.front = 0; // 앞 (나가는 곳)
    this.rear = 0; // 뒤 (들어오는 곳)
  }

  // 큐에 추가된 데이터의 크기를 리턴
  // front = 0, rear = 1, 지금 큐에 들어가 있는 데이터의 갯수는 몇 개인가요? 1
  size() {
    return this.rear - this.front; // 1 - 0 = 1
  }
	
	// 큐에 데이터를 추가 할 수 있어야 합니다.
  enqueue(element) {
    // front = 0, rear = 0
    this.storage[this.rear] = element;
    this.rear += 1;
  }
	
	// 가장 먼저 추가된 데이터가 가장 먼저 추출되어야 합니다.
  // 삭제한 데이터를 리턴
  dequeue() {
    // 빈 큐에 dequeue 연산을 적용해도 에러가 발생하지 않아야 합니다
    if (this.size() === 0) {
      return 0;
    }

    const result = this.storage[this.front];
    delete this.storage[this.front];
    this.front += 1; // 포인터도 한 칸 뒤로 // front는 0으로 초기 설정
    return result;
    
  }
}

'codes > 자료구조' 카테고리의 다른 글

[Stack] 구현  (0) 2023.02.12
[Stack] 구현  (0) 2023.01.15
[Stack] 브라우저 뒤로가기 앞으로가기  (0) 2023.01.12