데이터의 표현 및 저장 방법
후입선출(Last in, First out)
예시) 하노이의 탑
class Stack{
constructor(){
this.storage = {}; // 빈 객체
this.top = -1 // 최상단 요소의 인덱스(빈 배열일 경우 -1)
}
push(element)
)this.top
은 1 증가하고, 업데이트된 this.top
을 numeric key로 이용하여 값을 객체에 담는다.push(element){
this.top++; // ex) 빈 배열에 새 요소가 추가될 경우 top의 인덱스는 0이 된다.
this.storage[this.top] = element;
}
pop()
)pop() {
let temp; // 반환할 최상단 요소의 값
if (this.top === -1) {
reutnr {};
} else {
temp = this.storage[this.top];
delete this.storage[this.top];
this.top--;
return temp;
}
}
size()
)Stack의 크기(엘리먼트의 개수) 확인한다.
size() {
return this.top+1;
}
선입선출(First in, First out)
예시: 영화관 매표소 줄
class Queue {
constructor() {
this.storage = {};
this.front = 0; //가장 첫번째 요소의 인덱스값
this.rear = 0; // 가장 마지막 욧
}
enque(element)
)enqueue(element){
this.storage[this.rear] = element;
this.rear++; // 새로 추가될 요소의 인덱스값
}
dequeue(element){
let temp;
if (this.size() === 0) {
return {};
} else {
temp = this.storage[this.front];
delete this.storage[this.front];
this.front++;
return temp;
}
}
size() {
return this.rear - this.front;
}