Stack
stack은 ‘쌓다’라는 뜻을 가지고 있으며 접시를 쌓아 놓은 형태와 비슷한 자료구조
stack은 가장 나중에 들어간 자료가 가장 먼저 나오는 LIFO(Last In First Out)형태의 자료구조이다.
- stack 사용 예) 웹브라우저의 뒤로 가기, 앞으로 가기
✅ Stack 용어
✅ 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 용어
✅ 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;
}
}