스택 (Stack)
- 나중에 넣은 데이터가 먼저 나오는 LIFO(Last ln First put) 기반의 선형 자료 구조.
- 배열과 함께 알고리즘에서 많이 사용되는 자료 구조.
실사용예제
ctrl+z
- 웹브라우저에서 사이트를 탐색할 때 네이버 -> 카카오 -> 배민으로 페이지 이동을 한 경우
뒤로가기버튼을 누르면 카카오 페이지로 이동하는 원리
구현 메서드(method)
- 데이터 전체 획득 / 비어 있는지 확인: Stack.getBuffer(), Stack.isEmpty()
- 추가 / 삭제 / 마지막 데이터 조회 / 크기 확인 : Stack.push() Stack.pop(), Stack.peak(), Stack.size()
- 데이터 위치 / 존재 여부 확인: Stack.indexOf(), Stack.includes()
1. getBuffer() , isEmpty()
function Stack(array) {
this.array = array ? array : [];
}
Stack.prototype.getBuffer = function () {
return this.array.slice();
}
Stack.prototype.isEmpty = function () {
return this.array.length === 0;
}
let stack = new Stack([1, 2, 3]);
console.log(stack);
let data = stack.getBuffer();
console.log(data);
console.log(stack === data);
console.log(stack.isEmpty());
2. push(), Pop(), peek(), size()
Stack.prototype.push = function(element){
return this.array.push(element)
}
Stack.prototype.pop = function() {
return this.array.pop();
}
Stack.prototype.peek = function() {
return this.array[this.array.length-1];
}
Stack.prototype.size = function () {
return this.array.length;
}
let stack = new Stack([1,2]);
console.log(stack)
stack.push(3);
console.log(stack)
console.log(stack.pop());
console.log(stack)
console.log(stack.peek())
console.log(stack.size())
3. indexOf(), includes()
Stack.prototype.indexOf = function (element, position = 0) {
for (let i = position; i < this.array.length; i++) {
if (element === this.array[i]) return i;
}
return -1;
}
Stack.prototype.includes = function (element, position===0) {
for (let i = 0; i < this.array.length; i++) {
if (element === this.array[i]) return true;
}
return false;
}
let stack = new Stack([1, 2, 3]);
console.log(stack.indexOf(1));
console.log(stack.indexOf(2));
console.log(stack.indexOf(1, 2))
console.log(stack.includes(1))