스택: 바닥이 닫힌 원통, LIFO
예) 브라우저 히스토리, 이전작업취소
큐: 앞뒤가 뚫려있는 원통, FIFO
예) 레스토랑 앱, 예매 앱
그럼 어떻게 구조를 만들까?
배열의 장점: 서로 연관되어 있기 때문에 속도가 빠르지만, 할당된 메모리를 다 사용하면
복사해야하기때문에 조금더 사용할수도있다
큐는 앞의 요소를 제거할때 그때 index를 다시 조정해야하기 때문에 O(n)이 된다
class Node {
constructor(value){
this.value = value;
this.next = null;
}
}
class Stack {
constructor(){
this.top = null;
this.bottom = null;
this.length = 0;
}
peek() {
// stack에 쌓인 가장 마지막 녀석을 확인하는 메소드
return this.top;
}
push(value){
const newNode = new Node(value);
if (this.length === 0) {
this.top = newNode;
this.bottom = newNode;
} else {
const holdingPointer = this.top;
this.top = newNode;
this.top.next = holdingPointer;
}
this.length++;
return this;
}
pop(){
if (!this.top) return null;
if (this.top === this.bottom) {
this.bottom = null;
}
this.top = this.top.next;
this.length--;
return this;
}
//isEmpty
}