IT,프로그래밍/알고리즘

[자료구조] 스택(Stack)이란?

스택이란 자료구조중에서 선형구조에 해당하는 자료구조입니다.

 

 

쉽게 생각할수 있는것은 프링글스를 연상하시면 편합니다

 

 

위에는 뚫려있고, 위에서 부터 가져올수 있으며 반대로는 뺄수없는 형태를 스택구조 라고합니다

 

이것을 FILO(First In Last Out) 혹은 LIFO(Last In First Out) 혹은 선입후출 이라고 합니다

 

스택에는 몇가지 대표적인 행동(함수)가 있습니다

  • pop : 스택에서 맨위의 data를 꺼낸다 (감자칩을 꺼낸다)
  • push : 스택의 맨위에 data를 넣는다 (감자칩을 넣는다)
  • peek : 스택의 맨위의 data 를 조회한다 (맨위의 감자칩을 살펴본다)

이해를 돕기 위해 아래의 이미지를 보시면 좋습니다!

 

stack gif 이미지 검색결과

이러한 스택 개념을 코드로 옮겨서 구현을 할수가 있습니다

 

class Stack {
  constructor() {
    this._arr = [];
  }
  push(item) {
    this._arr.push(item);
  }
  pop() {
    return this._arr.pop();
  }
  peek() {
    return this._arr[this._arr.length - 1];
  }
  clear() {
    this._arr = [];
  }
  length() {
    return this._arr.length;
  }
}

const stack = new Stack();

위와 같이 Stack을 Class로 만들어서 사용할수 있습니다.

 

혹시 Stack자체를 직접 한들어서 쓰고 싶다라고 하신다면 아래의 코드를 참고하시면 됩니다.

 

const Stack = () => {
  this.dataStore = [];
  this.top = 0;
  this.push = push;
  this.pop = pop;
  this.peek = peek;
  this.clear = clear;
  this.length = length;
};

const push = (element) => {
  this.dataStore[this.top++] = element;
};

const pop = () => {
  return this.dataStore[--this.top];
};

const peek = () => {
  return this.dataStore[this.top - 1];
};

const clear = () => {
  this.top = 0;
};
const length = () => {
  return this.top;
};