
LIFO(Last In First Out, 후입선출) 의 구조를 가지는 자료구조
아래부터 쌓이고, 다음 저장되는 데이터는 바로 그 위에 쌓임
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
this.bottom = null;
this.length = 0;
}
/* top을 확인하는 메서드 */
peek() {
return this.top;
}
/* 스택에 새로운 데이터를 저장 */
push(value) {
const newNode = new Node(value);
if (!this.length) {
this.top = newNode;
this.botton = newNode;
} else {
const temp = this.top;
this.top = newNode;
this.top.next = temp;
}
this.length++;
}
/* top에서 데이터를 제거하는 메서드*/
pop() {
if (!this.top) return null;
if (this.top === this.bottom) {
this.bottom = null;
}
const popItem = this.top;
this.top = this.top.next;
this.length--;
return popItem.value;
}
/* 스택이 비었는지 확인하는 메서드 */
isEmpty() {
return this.length === 0;
}
}
const stack = new Stack();
stack.push("1");
stack.push("2");
stack.push("3");
console.log(stack.isEmpty()); // false
console.log(stack.pop()); // 3
console.log(stack.pop()); // 2
console.log(stack.pop()); // 1
console.log(stack.isEmpty()); // true