자료구조|알고리즘
JS. 스택 - 코딩테스트 광탈 방지, A to Z : JavaScript
(*ᴗ͈ˬᴗ͈)ꕤ*.゚
2022. 8. 28. 15:31
간단 정의
Last In First Out (LIFO)
배열로 구현
const stack = [];
stack.push(1);
stack.push(2);
stack.push(3);
console.log("🚀 ~ file: practice.js ~ line 5 ~ stack", stack);
// [1, 2, 3]
stack.pop();
console.log("🚀 ~ file: practice.js ~ line 10 ~ stack", stack);
//[1, 2]
// get top
console.log(stack[stack.length - 1]);
// 2
Linked List로 구현
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
this.size = 0;
}
push(value) {
const node = new Node(value);
node.next = this.top;
this.top = node;
this.size += 1;
}
pop() {
const value = this.top.value;
this.top = this.top.next;
this.size -= 1;
return value;
}
size() {
return this.size;
}
}