한 쪽 끝에서만 자료를 넣고 뺄 수 있는 LIFO(Last In First Out) 형식의 자료구조 이다.
- push : 스택에 element를 넣는다.
- pop : 스택의 최상단에서 element를 반환 후 제거. 시간복잡도는 O(1)
- peek : 스택의 최상단 element를 반환. 시간복잡도는 O(1)
- empty : 스택이 비어있는지 검사함. 시간복잡도는 O(1)
- size : 스택의 크기를 반환. 시간복잡도는 O(1) or O(n)
class Stack {
constructor() {
this.stack = new Map();
this.index = 0; //push, pop할 때마다 증가 및 감소
}
size() {
return this.stack.size;
}
empty() {
return this.stack.size > 0 ? false : true;
}
push(element) {
this.stack.set(this.index++, element);
}
pop() {
let temp;
if (this.stack.size > 0) {
temp = this.stack.get(this.index - 1);
//push연산 후 index를 증가시키기 때문에 현재 index-1 위치의 값을 출력함
this.stack.delete(this.index-- - 1);
}
return temp;
}
peek() {
const temp = this.stack.get(this.index - 1);
return temp;
}
}
- constructor
=> 생성자 함수로써 클래스가 선언되어 인스턴스화 되면, 객체를 생성할 때 객체의 초기 값을 설정해줌.
- this.stack
=> 자바스크립트의 Map 자료형을 이용하여 stack을 구성하였음
- this.index
=> index의 값을 이용해 push, pop, peek 연산 때 사용한다.
console.log(stack);
stack.push(5);
stack.push(5);
console.log(stack);
console.log(stack.peek(), stack.pop(), stack.size(), stack.empty());
결과는 다음과 같다.