오늘 뭐했냐/개발에 대한 주저리

23.07.25 스택(Stack) 구현하기

스스로에게 2023. 7. 26. 23:28

여기저기 찾아보면서 만들었다. 각자 만든 방식이 다른데 나는 객체에 담아서 구현을 했다. 먼저 내가 구현하기 위해 필요한 것들을 생각해보니 비어있는 경우, 크기 확인, 가장 위에 데이터, 데이터 추가, 데이터 제거가 필요했다. 그래서 아래와 같이 코드를 만들었다.

 

class Stack {
    constructor() {
        this.storage = {}
        this.size = 0
    }

    isEmpty() {
        return this.size < 1
    }
    isSize() {
        if (this.isEmpty()) return 0
        return this.size
    }
    top() {
        return this.storage[this.size]
    }
    push(item) {
        this.size++;
        this.storage[this.size] = item
    }
    pop() {
        if (this.isEmpty()) return "데이터가 없습니다"
        const popData = this.storage[this.size];
        delete this.storage[this.size];
        this.size--;
        return popData;
    }
}

const stack = new Stack
stack.push("a")
stack.push("b")
stack.push("c")
console.log(stack)
console.log(stack.pop())
console.log(stack.pop())
console.log(stack.pop())
console.log(stack.pop())
console.log(stack.isSize())
console.log(stack.isEmpty())

사실 배열에서 push(), pop() 메서드를 활용하면 훨씬 더 편하게 구현할 수 있고 속도도 더 빠르다. 하지만 직접 이렇게 구현해보는게 구조를 확실히 이해하고 내가 생각하는 것을 구현하는 능력을 성장시킬 수 있을 것 같아 이렇게 만들었다.