Stack은 한 쪽 끝에서만 자료구조를 넣고 뺄 수 있는 LIFO(Last IN First Out) 형식의 자료구조이다.
즉, 가장 최근에 스택에 추가된 데이터를 가장 먼저 삭제하는 것을 말한다.
size()
-현재 this.top
를 반환한다. 만약 this.top가 0보다 작게 될경우 0을 리턴한다.push(element)
- 주어진 element를 stack에 추가합니다. 현재 this.top
를 this.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;
Queue는 한 쪽 끝에서만 자료구조를 넣고 뺄 수 있는 LIFO(Last IN First Out) 형식의 자료구조이다.
즉, 가장 최근에 스택에 추가된 데이터를 가장 먼저 삭제하는 것을 말한다.
size()
- this.rear
과 this.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;