Last In First Out(선입후출)이라는 개념을 가진 선형 자료구조 입니다.
바닥이 막힌 상자를 생각하면 쉽게 이해하실 수 있습니다.
스택 메모리
는 함수가 실행되면 지역변수, 매개변수가 저장되는 메모리 영역입니다.
다음 코드가 실행되면 어떤일이 발생할까요?
fucntion sum(a, b) {
return a + b;
}
function print(value) {
console.log(value);
}
print(sum(5, 10))
const stack = []
// push
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack); // [1, 2, 3]
// pop
stack.pop();
console.log(stack); // [1, 2]
// get Top
console.log(stack[stack.length - 1]); // 2
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++
}
pop() {
const value = this.top.value;
this.top = this.top.next;
this.size--
return value;
}
size() {
return this.size;
}
}
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop()); // 3
stack.push(4);
console.log(stack.pop()); // 4
console.log(stack.pop()); // 2