TIL: 자료구조 | 스택(Stack)

Lumpen·2023년 4월 25일
0

TIL

목록 보기
232/242

후입선출 원리에 따라 정렬된 컬렉션으로
항상 동일한 종단점에서 추가/삭제 된다

후입 선출이므로 그냥 배열을 사용하는 것이 가장 좋을것 같다

class Stack {
	#store
   	constructor() {
    	this.#store = []
    }
	
	push(value) {
    	this.#store.push(value)
    }

	pop() {
		return this.#store.pop()
    }
	
	peek() {
      	const store = this.#store
    	return store[store.length - 1]
    }
}

queue 자료구조를 이용해서 10진법 -> 2진법 으로 변경하는..

const binary = (number, arr=[]) => {
  if (number === 0) {
    let result = ""
    const len = arr.length
    for(let i=0; i<len; i++) {
      result += arr.pop()
    }
    return result
  }
  const quotient = Math.floor(number / 2)
  const remainder = number % 2

  arr.push(remainder)

  return binary(quotient, arr)
}

console.log(binary(10))
profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글