Queue Optimised
이전과 달리 items를 객체{}로 선언해주었다.
class Queue {
constructor() {
this.items = {}
this.rear = 0
this.front = 0
}
enqueue(element) {
this.items[this.rear] = element
this.rear++
}
dequeue() {
const item = this.items[this.front]
delete this.items[this.front]
this.front++
return item
}
isEmpty() {
return this.rear - this.front === 0
}
peek() {
return this.items[this.front]
}
size() {
return this.rear - this.front
}
print() {
console.log(this.items)
}
}
const queue = new Queue()
console.log(queue.isEmpty())
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
console.log(queue.size())
queue.print()
console.log(queue.dequeue())
console.log(queue.peek())
Circular Queue
큐를 전반적으로 다 사용하게끔 원형방식으로 되었는 큐.
구현한거 따라 쳐보긴 했는데.. 어후... 잘 안쓰는 것 치곤 굉장히 복잡하다.
class CircularQueue {
constructor(capacity) {
this.items = new Array(capacity); // 수용 갯수만큼의 요소를 가진 배열생성
this.capacity = capacity; //수용 갯수
this.currentLength = 0;
this.rear = -1; // 요소가 들어가면 0부터 시작함. -1은 값이 없는 상태를 의미
this.front = -1; // 요소가 들어가면 0부터 시작함. -1은 값이 없는 상태를 의미
}
isFull() {
return this.currentLength === this.capacity
}
isEmpty() {
return this.currentLength === 0
}
enqueue(element) {
if(!this.isFull()) { // 조건문의 부정
this.rear = (this.rear+1) % this.capacity //Full 상태는 rear이 증가 불가능한 상태
this.items[this.rear] = element
this.currentLength += 1
if(this.front === -1) { // front가 안바뀐 예외적 상황(나간게 없는 상태라 -1에서 대기중)
this.front = this.rear
}
}
}
dequeue() {
if(this.isEmpty()) {
return null
}
const item = this.items[this.front]
this.items[this.front] = null
this.front = (this.front + 1) % this.capacity
this.currentLength -= 1
if(this.isEmpty()) {
this.front = -1
this.rear = -1
}
return item
}
peek() {
if(!this.isEmpty()) {
return this.items[this.front]
}
return null
}
print() {
if(this.isEmpty()) {
console.log('Queue is empty')
} else {
let i
let str = ''
for(i = this.front; i !== this.rear; i = (i + 1) % this.capacity) {
str += this.items[i] + " "
}
str += this.items[i]
console.log(str)
}
}
}
const queue = new CircularQueue(5)
console.log(queue.isEmpty())
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.enqueue(40)
queue.enqueue(50)
console.log(queue.isFull())
queue.print()
console.log(queue.dequeue())
console.log(queue.peek())
queue.print()
queue.enqueue(60)
queue.print()
'📈알고리즘 > 자료구조(js)' 카테고리의 다른 글
js 자료구조(1)[Stack, Queue] (0) | 2023.03.16 |
---|