[JS자료구조] 스택(stack)

youngseo·2022년 2월 14일
post-thumbnail

스택 (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()

//stack(): 생성자 함수
function Stack(array) {
  this.array = array ? array : []; //default값으로 설정해도 좋습니다.
}

//getBuffer(): 객체 내 데이터 셋 반환
Stack.prototype.getBuffer = function () {
  return this.array.slice();
}

//isEmpty(): 객체 내 데이터 여부 확인
Stack.prototype.isEmpty = function () {
  return this.array.length === 0;
}
//정상적 동작 확인
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(stack === data); //false

console.log(stack.isEmpty()); //false

2. push(), Pop(), peek(), size()

//push(): 데이터 추가
Stack.prototype.push = function(element){
  return this.array.push(element)
}

//pop(): 데이터 삭제
Stack.prototype.pop = function() {
  return this.array.pop();
}

//peek() : 가장 끝 데이터 반환
Stack.prototype.peek =  function() {
  return this.array[this.array.length-1];
}

//size(): 스택 내 데이터 개수 확인
Stack.prototype.size = function () {
  return this.array.length;
}
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) //Stack { array: [ 1, 2 ] }
console.log(stack.peek()) //2
console.log(stack.size()) //2

3. indexOf(), includes()

//indexOf(): 매개변수로 넘어온 element 위치 확인
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;
  // return this.array.indexOf(element, position);
}

//includes(): 데이터 존재 여부 확인
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;
  //  return this.array.includes(element)
}
let stack = new Stack([1, 2, 3]);

console.log(stack.indexOf(1)); //0
console.log(stack.indexOf(2)); //1
console.log(stack.indexOf(1, 2)) //-1
console.log(stack.includes(1)) //true

0개의 댓글