하나의 진입점에서만 자료를 넣고 뺄 수 있는 LIFO(Last In First Out) 형식의 자료구조.
스택은 연결리스트(linked list) 로 구현할 수 있다.
스택의 맨 위에 value를 삽입한다.
가장 나중에 들어간(맨 위) 요소를 삭제 후 반환한다.
return this.size
스택의 크기를 반환한다.
return this.top
스택의 맨 위 요소를 반환한다.
return this.top === null
스택이 비었는지 확인한다.
class Node {
constructor(data) {
this.next = null;
this.data = data;
}
}
class Stack {
constructor() {
this.top = null;
this.size = 0;
}
getSize(){
return this.size;
}
push(data){
const node = new Node(data);
node.next = this.top;
this.top = node;
this.size++;
}
pop(){
if(this.size === 0) return null;
const temp = this.top.data;
this.top = this.top.next;
this.size--;
return temp;
}
}