🔗 Stack 구현

데브캠프 내에서 그룹스터디를 진행하면서 우리 그룹의 멘토님께서 이번주의 과제를 주셨다.

자료구조 Stack의 구조로 로직을 구현하는 것.

위의 사진과 같이 기본적인 틀은 제공해주셨고 배열이 아닌 객체로 선언해주셨다. 객체 stack의 크기와 데이터를 넣고 빼내는 로직을 구현해보는 것이다.

🔗 Stack

자료구조 스택은 데이터가 들어올때 하나씩 쌓이면 나갈땐 나중에 들어온 데이터가 빠지는 구조이다. 즉, 먼저 들어온 데이터는 제일 나중에 빠진다. 스택의 연산에서 대표적으로는 스택에 데이터를 삽입하는 push(), 스택에서 데이터를 삭제하여 반환하는 pop()이 있다.

📖 stack size( ) 로직

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

  // stack의 크기(데이터의 개수)를 알 수 있어야 합니다.
  size() {
    this.count = Object.keys(this.storage).length
    return this.count
  }
}
  
const sta = new Stack()
console.log(sta.size()) // 0

Object.keys()를 사용하여 객체의 키 값을 문자열 배열로 바꿔주었다. 객체의 value 값을 반환하고싶으면 Object.value()를 사용하면 된다.
this.storage 객체를 배열로 바꾸고 배열의 길이를 this.count 로 선언했다.

📖 stack push( ) 로직

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

  // stack에 데이터를 넣을 수 있어야 합니다.
  push(a) {
	this.storage[this.count + 1] = a
    this.count++
  }
}
  
const sta = new Stack()
sta.push("a")
sta.push(222)
sta.push(999)
console.log(sta.storage)
// {1: 'a', 2: 222, 3: 999}
console.log(sta.count)
// 3

this.storage의 키를 this.conut + 1 로 입력해주고 파라미터 a 를 this.count + 1의 value로 넣어 준 뒤, this.count를 ++ 증가시켜주었다.
스택의 push()를 3번 실행해준 뒤 storage와 count를 출력해주니 스택에 데이터를 넣고 사이즈를 확인 할 수 있었다.

📖 stack pop( ) 로직

class Stack {
  constructor() {
    this.storage = {}
    this.count = 0
  }
  
  // stack에서 데이터를 빼내어 값을 확인 할 수 있어야 합니다.
  pop() {
    let arr = Object.keys(this.storage) 
    let endIndex = arr.length - 1
    delete this.storage[arr[endIndex]]
    this.count = Object.keys(this.storage).length
  }
}

sta.pop()
console.log(Object.keys(sta.storage))
// ['1', '2']
console.log(sta.count)
// 2

sta.pop()
console.log(Object.keys(sta.storage))
// ['1']
console.log(sta.count)
// 1

pop( )이후 storage의 키를 배열로 출력하고싶어서 storage를 배열로 선언하고 가장 끝에있는 인덱스의 키 값을 삭제해주기 위해 마지막 인덱스도 선언해주었다. 이후 delete 연산자를 사용하여 storage의 배열의 키 값의 가장 끝 인덱스 키 값을 제거해주었고 이후 count도 한번 더 선언했다. 이후 스택의 pop( )을 실행할때마다 가장 마지막에 있는 인덱스가 제거 된다.

🔗 정리

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

  // stack의 크기(데이터의 개수)를 알 수 있어야 합니다.
  size() {
    this.count = Object.keys(this.storage).length
    return this.count
  }

  // stack에 데이터를 넣을 수 있어야 합니다.
  push(a) {
	this.storage[this.count + 1] = a
    this.count++
  }

  // stack에서 데이터를 빼내어 값을 확인 할 수 있어야 합니다.
  pop() {
    let arr = Object.keys(this.storage)
    let endIndex = arr.length - 1
    delete this.storage[arr[endIndex]]
    this.count = Object.keys(this.storage).length
  }
}

const sta = new Stack()
console.log(sta.size())
sta.push("a") 
sta.push(222)
sta.push(999)
console.log(sta.storage) 
// {1: 'a', 2: 222, 3: 999}
console.log(sta.count) 
// 3

sta.pop()
console.log(Object.keys(sta.storage))
// ['1', '2']
console.log(sta.count)
// 2

sta.pop()
console.log(Object.keys(sta.storage))
// ['1']
console.log(sta.count)
// 1

내가 작성한 로직이 정답이라고는 생각하지 않는다 ! 더 공부를 한 이후에 다시 작성하게되면 달라질 수 있는 로직...
생성되어있는 클래스의 함수를 실행시키고 호출하는 과정이 정말 편했지만 편한만큼 함수내부의 로직을 깔끔하게 구현하기가 어려웠다.

profile
성장하는 과정에서 성취감을 통해 희열을 느낍니다⚡️

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN