나중에 넣은 데이터가 먼저 나오는 LIFO(Last In First Out) 기반의 선형 자료 구조이다.
LIFO를 쉽게 이해하려면 팬케이크를 떠올리면 된다!
팬케이크는 1,2,3 순서대로 접시에 놓고 3,2,1 순으로 먹는다 요걸 기억하면댐ㅋㅋ
우리 일상에서 쉽게 접할만한 스택 기반 :
문서를 작성할 때 ctrl + z, 웹브라우저 페이지 이동(뒤로가기) 등
function Stack(array){
this.array = array ? array : [];
// array 가 있을 경우 this.array = array
// array 가 없을 경우 this.array = []
}
getBuffer() : 객체 내 데이터 셋 반환(this.array를 복사 후 반환)
Stack.prototype.getBuffer = function(){
return this.array.slice();
};
isEmpty() : 객체 내 데이터 존재 여부 파악
Stack.prototype.isEmpty = function(){
return this.array.length == 0;
};
// Test code : getBuffer(), isEmpty()
let stack = new Stack([1, 2, 3]);
console.log(stack); // Stack { array: [ 1, 2, 3 ] }
let data = stack.getBuffer();
console.log(data); // [ 1, 2, 3 ]
console.log(data === stack.array); // false
console.log(stack.isEmpty()); // false
console.log(Object.getOwnPropertyDescriptors(Stack.prototype)); // 객체 내부 확인
push() : 데이터 추가
Stack.prototype.push = function(element){
return this.array.push(element);
};
pop() : 데이터 삭제
Stack.prototype.pop = function(){
return this.array.pop();
};
peak() : 가장 끝 데이터 반환
Stack.prototype.peek = function(){
return this.array[this.array.length - 1];
};
size() : 스택 내 데이터 개수 확인
Stack.prototype.size = function(){
return this.array.length;
};
// Test code : push(), pop(), peak(), size()
let stack = new Stack([1, 2]);
console.log(stack); // Stack { array: [ 1, 2 ] }
stack.push(3);
console.log(stack); // Stack { array: [ 1, 2, 3 ] }
console.log(stack.pop()); // 3
console.log(stack.pop()); // 2
console.log(stack.peek()); // 1
console.log(stack.size()); // 1
indexOf() : 데이터 위치 값 조회
Stack.prototype.indexOf = function(element, position = 0){
/* case 1 */
// return this.array.indexOf(element, position);
/* case 2 */
for(let i = position; i < this.array.length; i++){
if(element == this.array[i]) return i;
}
return -1;
};
includes() : 데이터 존재 여부 확인
Stack.prototype.includes = function(element, position = 0){
/* case 1 */
// return this.array.includes(element);
/* case 2 */
for(let i = position; i < this.array.length; i++){
if(element == this.array[i]) return true;
}
return false;
};
// Test code : indexOf(), includes()
let stack = new Stack([1, 2, 3]);
console.log(stack.indexOf(1)); // 0
console.log(stack.indexOf(1, 2)); // -1
console.log(stack.includes(1)); // true
console.log(stack.includes(1, 2)); // false